我正在使用React和mongodb开发一个小型CRUD全栈应用程序,并且在使用useEffect
向服务器发出axios获取请求以获取所有待办事项时遇到了这个问题。问题在于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
仅在待办事项更改时才打印,例如当我添加新的待办事项等时,而是永久打印。
答案 0 :(得分:0)
您说过,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)`.
}