如何使 react 的 useEffect 停止无限循环中的重新渲染,即使指定了依赖项?



我正在开发一个带有react和mongodb的小型CRUD全栈应用程序,我遇到了这个问题,我使用useEffect向服务器发出axios获取请求,以获取我的所有todo。问题是,useEffect完成了它的工作,但它也会重复到无穷大。这是我的组件:

export default function () {
...
const [todos, setTodos] = useState([]);
const currentUser = JSON.parse(localStorage.getItem('user'))._id;
useEffect(() => {
async function populateTodos () {
try {
const res = await axios.get(`http://localhost:8000/api/all-todos/${currentUser}`);
setTodos(res.data);
} catch (err) {
if (err.response) {
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
console.log(err.request);
} else {
console.log('Error: ', err.message);
}
}
}
populateTodos();
}, [todos]);
console.log(todos);
return (
...
);
}

因此,我所期望的是,console.log只有在todo更改时才会打印出来,比如当我添加一个新的todo等等时,但它会永远打印出来。

您说过首先需要获取todos,并且每当todos发生变化时都需要获取。我可以建议你一种不同的方法,再使用一个变量,比如这样:

const TodosComponent = (props) => {
const [todos, setTodos] = useState([]);
const [updatedTodos, setUpdatesTodos] = useState(true);
const fetchFunction = () => {
// In here you implement your fetch, in which you call setTodos().
}
// Called on mount to fetch your todos.
useEffect(() => {
fetchFunction();
}, []);
// Used to updated todos when they have been updated.
useEffect(() => {
if (updatedTodos) {
fetchFunction();
setUpdatesTodos(false);
}
}, [updatedTodos]);
// Finally, wherever you update your todos, you also write `updateTodos(true)`. 
}

最新更新