使用 useEffect() 时超出最大深度反应错误 [英] Maximum depth exceeded react error while using useEffect()

查看:59
本文介绍了使用 useEffect() 时超出最大深度反应错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误:警告:超出最大更新深度.当组件在 useEffect 中调用 setState 时,可能会发生这种情况,但 useEffect 要么没有依赖项数组,要么每次渲染时依赖项之一发生变化.

Error: Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

const [products, setProducts] = useState([]);

useEffect(() => {
  setProducts(getCartProducts());
}, [products]); 

当传递一个空数组作为第二个参数时,应用程序工作正常,但为了反映页面上的更改,我必须刷新它,但是在将items"对象作为数组中的第二个参数传递后,我收到上述错误.

When passing an empty array as the second argument, the app works fine but in order to reflect the changes on the page I have to refresh it, but after passing the 'items' object as the second argument in the array, I receive the above error.

推荐答案

const [products, setProducts] = useState([]);

useEffect(() => {
  setProducts(getCartProducts());
}, [products]); 

这相当于在没有任何条件的情况下在 componentDidUpdate 内部设置状态.您正在更新 useEffect 内的状态,这是正确的,但在 dependency array 内传递相同的状态作为将在您的 effect 内更新的参数是 错误.您应该设置更改您的依赖注入,您应该重新评估您的代码并相应地标记您的依赖数组.如果您将 products 设置为效果的依赖项数组,那么您只是说要在 products 更新和内部效果时做出反应,运行此效果只是更新products,所以没有任何意义,你可以做的一件事就是使用一个辅助状态来运行你的效果.

This is equivalent to setting state inside componentDidUpdate without any conditions. You are updating your state inside useEffect that is correct but passing your same state inside dependency array as an argument which will be updated inside your effect is wrong. You should set change your dependency injection and you should re-evaluate your code and mark your dependency array accordingly. If you are setting products as your effect's dependency array then your are just saying to react that run this effect whenever products updated and inside effect you are just updating products, so it does not make any sense, one thing you can do is use an auxiliary state for running your effect.

这篇关于使用 useEffect() 时超出最大深度反应错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆