javascript - 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 参数?
解决方案
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
.
推荐阅读
- python - Chrome 已关闭并出现错误错误:network_change_notifier_win.cc(141)] WSALookupServiceBegin 失败,原因为:0
- pyspark - 在 group 和 agg 之后显示所有 pyspark 列
- amazon-web-services - ask-cli, Ask deploy, UnrecognizedClientException: 请求中包含的安全令牌无效
- java - 使用递归除法的迷宫生成器
- javascript - 按顺序生成数字 Order
- angular - Angular PrimeNG - 如何更改 rowsperpageoptions 在 p-paginator 标记中生成的 p-dropdown 样式
- python - 在 python 的固定或更改长度表中显示打印结果
- reactjs - html 中的 Jest 覆盖率报告缺少覆盖率值
- python - pynput 键盘侦听器导致延迟
- python - 从头开始创建二级/内部索引