[英]How to make useEffect only run once on component mount without lying to React?
If I want useEffect
to only run once on component mount, what is the right way of doing it?如果我希望
useEffect
只在组件挂载上运行一次,那么正确的做法是什么? Check the following example:检查以下示例:
const UseEffectCounter1 = () => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, []);
return (
<div>
<button onClick={() => {setCount(count + 1)}}>+1</button>
</div>
)
}
Re-renders are prevented due to []
being passed as dependency array.由于
[]
作为依赖数组传递,因此阻止了重新渲染。 Code running fine, no errors.代码运行良好,没有错误。 'You clicked 0 times' shows only once, click the button does nothing, which fits the purpose 'only run once on the component mount'.
'You clicked 0 times'只显示一次,点击按钮什么都不做,符合'只在组件挂载上运行一次'的目的。
However this is lying to React and not recommended in Dan Abramov's article here .然而,这是对 React 的欺骗,并且在 Dan Abramov 的文章中不推荐。 I should pass the dependency to the dependency array, which is warned as
React Hook useEffect has a missing dependency: 'count'
.我应该将依赖项传递给依赖项数组,当
React Hook useEffect has a missing dependency: 'count'
。 However if I pass [count]
in the dependency array, useEffect
starts updating after component mount.但是,如果我在依赖数组中传递
[count]
,则useEffect
在组件挂载后开始更新。
What is the correct way of making useEffect
only update on component mount?使
useEffect
仅更新组件安装的正确方法是什么?
As mentioned in the comment, there is no point in making the useEffect
hook dependent on the count
, if you are not going to update the title every time the count changes.如评论中所述,如果您不打算在每次计数更改时更新标题,则使
useEffect
挂钩依赖于count
是没有意义的。 The code could be:代码可以是:
const UseEffectCounter1 = () => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = 'You clicked 0 times';
}, []);
return (
<div>
<button onClick={() => {setCount(count + 1)}}>+1</button>
</div>
)
}
Anyway, if you really want to avoid the hard-coded value, you could do something like:无论如何,如果您真的想避免硬编码值,您可以执行以下操作:
const UseEffectCounter1 = () => {
const initCount = 0;
const [count, setCount] = useState(initCount);
useEffect(() => {
document.title = `You clicked ${initCount} times`;
}, [initCount]);
return (
<div>
<button onClick={() => {setCount(count + 1)}}>+1</button>
</div>
)
}
As initCount
is never going to change, the useEffect hook will be triggered only once.由于
initCount
永远不会改变,useEffect 挂钩只会被触发一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.