[英]useEffect infinite loop with axios
I'm stuck in an infinite loop in useEffect despite having tried the clean up function尽管已尝试清理 function,但我仍陷入 useEffect 的无限循环
I tried to pass [] and [usersDB] as the 2nd parameter of useEffect and it didn't work because [] makes it run only one time and it's not the behavior I'm looking for (I want it to run after each update)我试图将 [] 和 [usersDB] 作为 useEffect 的第二个参数传递,但它不起作用,因为 [] 使它只运行一次,这不是我正在寻找的行为(我希望它在每次更新后运行)
const ListUsers = () => {
const [usersDB, setUsersDB] = useState([]);
useEffect(() => {
const getUsers = async () => {
const response = await axios
.get("http://localhost:4000/contacts")
.catch((error) => console.log(error.resp));
setUsersDB(response.data);
};
getUsers();
});
console.log(usersDB);
return (
<div>
<div>
{usersDB.map((user, index) => (
<CardUsers key={user._id} user={user} />
))}
</div>
</div>
);
};
export default ListUsers;
Every time the component renders, it runs your useEffect
.每次组件呈现时,它都会运行您的
useEffect
。 Your useEffect
calls setUsersDB
, which updates state, which causes a rerender, which runs useEffect
...您的
useEffect
调用setUsersDB
,它更新 state,这会导致重新渲染,运行useEffect
...
You can add an array of values at the end of useEffect
which tells the useEffect
to only run if any of the included values have changed.您可以在
useEffect
的末尾添加一个值数组,它告诉useEffect
仅在包含的任何值发生更改时才运行。 But if you add an empty array, it tells the useEffect
to run only once, and never again, as there are no values that it depends on that have changed.但是,如果您添加一个空数组,它会告诉
useEffect
只运行一次,而不会再运行一次,因为它所依赖的值没有发生变化。 You mention that you tried this, and that you want useEffect
to run after each update.您提到您尝试过这个,并且您希望
useEffect
在每次更新后运行。 Each update of what?每次更新什么? If there is some other value that is being updated elsewhere, and you want
useEffect
to be dependent on that value, then stick it in the dependency array.如果其他地方正在更新一些其他值,并且您希望
useEffect
依赖于该值,则将其粘贴到依赖项数组中。
useEffect(() => {
const getUsers = async () => {
const response = await axios
.get("http://localhost:4000/contacts")
.catch((error) => console.log(error.resp));
setUsersDB(response.data);
};
getUsers();
}, [some updating value])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.