首页 > 解决方案 > React Infinite loop useEffect 当参数具有默认数组时

问题描述

它从来没有发生在我身上,我不知道为什么会这样。

我有这两个组件在子组件的 useEffect 中创建无限循环:

function Container(){
  return <div> <Description /> </div>
}

// If I remove "= []" part no infinite loop is created
function Description({list = []}){
  const [dict, setDict] = useState({})

  useEffect(() => {
      console.log('this is for the inifinite loop log')
      setDict({}) // also, If a remove this line no infinite loop is created
  }, [list]) 

  return <div>something...</div>
}

** 已编辑:此代码只是我的问题的简化 **

我知道每次重新渲染组件时都会使用不同的内存指针创建默认数组,但是没有办法将列表作为默认道具并同时将其用作 useEffect 参数?

标签: javascriptreactjsjsx

解决方案


When the state of the function component of React changes, the function is called again. And when the state of the function component changes, if the dependence array of useEffect also changes, the callback in useEffect is called.

When setDict is called in the above code, a new instance of the array, which is the default value to be put in the list, is created every time, so useEffect update callback continues to be called.

So you can use an empty array as the default by using the same array of instances.

const emptyArray = [];
// If I remove "= []" part no infinite loop is created
function Description({list = emptyArray}){
  const [dict, setDict] = useState({})

  useEffect(() => {
      console.log('this is for the inifinite loop log')
      setDict({}) // also, If a remove this line no infinite loop is created
  }, [list]) 

  return <div>something...</div>
}

I don't know what the final purpose you want just by looking at the example code above. I think your code creates a parameter of setDict by processing the list from your parent component. In general, I think that the parent of Description sends only the array or empty array value to the list prop. If so, I think it's a better way to cause an error when the array does not come in without supporting the empty array, which is the default of the list.


推荐阅读