简体   繁体   English

React - 使用反应钩子,在 useEffect 中设置一个数组 state 并观察它导致无限循环?

[英]React - Use react hooks, set an array state in useEffect and watch it cause Infinite loop?

Declare an custom hook:声明一个自定义钩子:

const useTest = (init: any) => {
  const [arr, setArr] = useState<any[]>([]);
  useEffect(() => {
    setArr(Array.from(init.arr));
  }, [init]);
  return arr;
};

Use it:用它:

useTest({ arr: [1] })

No matter what object or array did I pass to the init.arr, it would cause a infinite loop.无论我将什么 object 或数组传递给 init.arr,都会导致无限循环。 I tried to wrap the init object by useMemo, it`s useless.我试图用useMemo包装init object,它没用。 But if i pass a (string | number | null | undefined), it won`t get error.但是如果我通过 (string | number | null | undefined),它不会出错。

I test it use '@testing-library/react-hooks' with jest.我开玩笑地使用'@testing-library/react-hooks'来测试它。 What`s more it only occur in my test case, but runs well in browser.更重要的是它只发生在我的测试用例中,但在浏览器中运行良好。

So what cause that?那是什么原因造成的呢?

you need to pass }, []);你需要通过}, []); as shown below to load useffect only once when component is loaded.如下图在加载组件时只加载一次useffect。 it also should remove any infinite loop problems它还应该消除任何无限循环问题

React.useEffect(() => {
   setArr(Array.from(init.arr));
 }, []);
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM