React hook useEffect连续运行/无限循环 [英] React hook useEffect runs continuously forever/infinite loop
问题描述
我正在尝试新的 React Hooks 的 useEffect
API,它似乎永远在无限循环中继续运行!我只希望 useEffect
中的回调运行一次。这是我的参考代码:
I'm trying out the new React Hooks's useEffect
API and it seems to keep running forever, in an infinite loop! I only want the callback in useEffect
to run once. Here's my code for reference:
点击运行代码片段,看到Run useEffect字符串无限打印到控制台。
function Counter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('Run useEffect');
setCount(100);
});
return (
<div>
<p>Count: {count}</p>
</div>
);
}
ReactDOM.render(<Counter />, document.querySelector('#app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
推荐答案
这是因为 useEffect
是每次渲染后触发,这是在这种无状态功能组件的情况下调用 Counter()
函数。当您在 useEffect
setX 从 useState
返回的调用时>,React将再次呈现该组件,并再次运行 useEffect
。这会导致无限循环:
This happens because useEffect
is triggered after every render, which is the invocation of the Counter()
function in this case of stateless functional components. When you do a setX
call returned from useState
in a useEffect
, React will render that component again, and useEffect
runs again. This causes an infinite loop:
Counter()
→ useEffect()
→ setCount()
→ Counter()
→ useEffect()
→...(循环)
Counter()
→ useEffect()
→ setCount()
→ Counter()
→ useEffect()
→ ... (loop)
要使 useEffect
只运行一次,请传递一个空数组 []
作为第二个参数,如下面修订的片段所示。
To make your useEffect
run only once, pass an empty array []
as the second argument, as seen in the revised snippet below.
第二个参数的意图参数是在数组参数中的任何值更改时告诉React:
The intention of the second argument is to tell React when any of the values in the array argument changes:
useEffect(() => {
setCount(100);
}, [count]); // Only re-run the effect if count changes
您可以将任意数量的值传入数组和 useEffect
只有在任何一个值发生变化时才会运行。通过传入一个空数组,我们告诉React不要跟踪任何更改,只运行一次,有效模拟 componentDidMount
。
You could pass in any number of values into the array and useEffect
will only run when any one of the values change. By passing in an empty array, we're telling React not to track any changes, only run once, effectively simulating componentDidMount
.
function Counter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('Run useEffect');
setCount(100);
}, []);
return (
<div>
<p>Count: {count}</p>
</div>
);
}
ReactDOM.render(<Counter />, document.querySelector('#app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
了解更多关于 useEffect 。
这篇关于React hook useEffect连续运行/无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!