英文:
Why is the following ReactJS code resulting in infinite re-render loop?
问题
以下是您要翻译的内容:
The following code intends to run useEffect whenever the __payload changes.
const Viewer = (props) => {
const __payload = JSON.parse(props.payload);
const [values, setValues] = useState([]);
useEffect( () => {
var __values = "value"; // passing in a sad string
setValues(__values);
}, [__payload]);
};
The issue arises when I pass an array value to setValues:
const Viewer = (props) => {
const __payload = JSON.parse(props.payload);
const [values, setValues] = useState([]);
useEffect( () => {
var __values = ["value"]; // passing in a needed array
setValues(__values);
}, [__payload]);
};
This results in an infinite loop and an error:
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
Why is that? The useEffect is specifically limited to run on a change to __payload variable.
英文:
The following code intends to run useEffect whenever the __payload changes.
const Viewer = (props) => {
const __payload = JSON.parse(props.payload);
const [values, setValues] = useState([]);
useEffect( () => {
var __values = "value"; // passing in a sad string
setValues(__values);
}, [__payload]);
};
The issue arises when I pass an array value to setValues:
const Viewer = (props) => {
const __payload = JSON.parse(props.payload);
const [values, setValues] = useState([]);
useEffect( () => {
var __values = ["value"]; // passing in a needed array
setValues(__values);
}, [__payload]);
};
This results in an infinite loop and an error:
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
Why is that? The useEffect is specifically limited to run on a change to __payload variable.
答案1
得分: 1
每次调用 JSON.parse 时,都会获得一个 'new' 对象,即使它看起来相同。从 React 的角度来看,每次渲染时 __payload
都已更改,导致调用 setValues
,进而引发另一个渲染。
根据您分享的代码,最简单的修复方法可能是将 useEffect
的依赖项更改为使用 props.payload
而不是 __payload
。
useEffect(() => {
var __values = "value"; // 传递一个悲伤的字符串
setValues(__values);
}, [props.payload]);
英文:
Every time you call JSON.parse you get a 'new' object, even if it looks the same. From the perspective of React, every time you render __payload
has changed, causing setValues
to be called, causing another render.
Based on the code you shared, the easiest fix is probably changing the useEffect
dependency to use props.payload
instead of __payload
.
useEffect( () => {
var __values = "value"; // passing in a sad string
setValues(__values);
}, [props.payload]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论