useEffect 中的无限循环 [英] Infinite loop in useEffect

查看:49
本文介绍了useEffect 中的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 React 16.7-alpha 中的新钩子系统,当我处理的状态是对象或数组时,我陷入了 useEffect 的无限循环.

I've been playing around with the new hook system in React 16.7-alpha and get stuck in an infinite loop in useEffect when the state I'm handling is an object or array.

首先,我使用 useState 并用这样的空对象启动它:

First, I use useState and initiate it with an empty object like this:

const [obj, setObj] = useState({});

然后,在useEffect中,我再次使用setObj将其设置为空对象.作为第二个参数,我传递了 [obj],希望如果对象的 内容 没有改变,它就不会更新.但它一直在更新.我猜是因为不管内容如何,​​这些总是不同的对象,让 React 认为它不断变化?

Then, in useEffect, I use setObj to set it to an empty object again. As a second argument I'm passing [obj], hoping that it wont update if the content of the object hasn't changed. But it keeps updating. I guess because no matter the content, these are always different objects making React thinking it keep changing?

useEffect(() => {
  setIngredients({});
}, [ingredients]);

数组也是如此,但作为原语,它不会像预期的那样陷入循环.

The same is true with arrays, but as a primitive it wont get stuck in a loop, as expected.

使用这些新的钩子,在检查天气内容是否改变时,我应该如何处理对象和数组?

Using these new hooks, how should I handle objects and array when checking weather the content has changed or not?

推荐答案

将空数组作为第二个参数传递给 useEffect 使其仅在挂载和卸载时运行,从而停止任何无限循环.

Passing an empty array as the second argument to useEffect makes it only run on mount and unmount, thus stopping any infinite loops.

useEffect(() => {
  setIngredients({});
}, []);

https://www.robinwieruch 上的关于 React 钩子的博客文章中向我阐明了这一点.de/react-hooks/

这篇关于useEffect 中的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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