useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('http://localhost:8888/todos');
console.log('Response:', response.data);
const todosWithBooleanDone = response.data.map(todo => ({
id: todo.id,
name: todo.name,
done: todo.done === 1,
}));
console.log('Setting todos:', todosWithBooleanDone);
setTodos(todosWithBooleanDone);
} catch (error) {
console.error('Error fetching todos:', error);
}
};
fetchData();
}, [todos]);
我预计不会有数百万个请求。
如果数组中没有依赖项待办事项,我的应用程序将无法运行!
我想添加一个新的 useEffect 但它不起作用。
我已经接近解决方案,但我真的不知道如何解决它。
每次
useEffect
有更新时,都会调用您的 todos
,并且您反复调用 setTodos
来更新 todos
,这会导致无限调用。
您的第一个
useEffect
可以没有依赖项,仅在组件安装上运行以获取和设置todos
。
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('http://localhost:8888/todos');
console.log('Response:', response.data);
const todosWithBooleanDone = response.data.map(todo => ({
id: todo.id,
name: todo.name,
done: todo.done === 1,
}));
console.log('Setting todos:', todosWithBooleanDone);
setTodos(todosWithBooleanDone);
} catch (error) {
console.error('Error fetching todos:', error);
}
};
fetchData();
}, []); // <-- Without dependency
另一个
useEffect
每次待办事项更改时运行。
useEffect(() => {
// Your code whenever todos changes.
}, [todos]); // <--- With dependency