[英]useEffect infinite loop when updating state and including dependency array
I always find this a bit weird with React that it is said to be an anti-pattern to not add all dependencies to the useEffect
hook and warnings are shown in the console.我总是觉得 React 有点奇怪,据说不将所有依赖项添加到
useEffect
挂钩是一种反模式,并且控制台中会显示警告。
Take this example.举个例子。 I am using
swr
and useSWRInfinite
- see example here and docs here .我正在使用
swr
和useSWRInfinite
- 请参阅此处的示例和此处的文档。
My code looks checks that a element is inView
and if so it fetches the next page of data.我的代码看起来检查元素是否在
inView
,如果是,它会获取下一页数据。
This all works fine这一切都很好
useEffect(() => {
if (inView) {
setSize(size + 1)
}
}, [inView, setSize])
but if I add size
to the dependency array an infinite loop occurs as I am updating the size
within useEffect
但是如果我将
size
添加到依赖项数组,则会在更新useEffect
中的size
时发生无限循环
useEffect(() => {
if (inView) {
setSize(size + 1)
}
}, [inView, setSize, size]) <------ everything breaks
Can anyone advise on the correct way of handling this.谁能建议正确的处理方法。 After reading through many SO answers and blog posts nothing is any clearer.
在阅读了许多 SO 答案和博客文章之后,没有什么比这更清楚了。
You have added size
in the dependency array.您已在依赖项数组中添加了
size
。 So, the useEffect
will run whenever size
changes.因此,只要
size
发生变化, useEffect
就会运行。 Now, in your useEffect
, you are incrementing size
using the setSize
setter.现在,在您的
useEffect
中,您正在使用setSize
设置器增加size
。 This will again cause size
to change and again run the useEffect
.这将再次导致
size
发生变化并再次运行useEffect
。
If you want to refer to the previous size
, you can use the callback version of the setSize
.如果要参考以前的
size
,可以使用setSize
的回调版本。
setSize((previousSize) => previousSize + 1)
This way, your linter won't complain.这样,您的 linter 就不会抱怨。
You aren't supposed to use the size state inside the setSize.您不应该在 setSize 中使用大小 state。 You can change it to
setSize(size => size + 1)
And then remove the size from the dependency array.您可以将其更改为
setSize(size => size + 1)
,然后从依赖数组中删除大小。 Can read more here: enter link description here可以在这里阅读更多:在这里输入链接描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.