[英]How can I use useEffect in React to run some code only when the component first mounts, and some other code whenever an event occurs (repeatedly)?
If the title wasn't clear, I want to run some code when the component mounts, and some other code when a particular variable changes.如果标题不清楚,我想在组件挂载时运行一些代码,并在特定变量更改时运行一些其他代码。 I could add the variable in the [], but the problem is, I want some code to run only once, and not when the variable changes.
我可以在 [] 中添加变量,但问题是,我希望某些代码只运行一次,而不是在变量更改时运行。
FYI: The variable is a window property仅供参考:变量是 window 属性
Thanks in advance!提前致谢!
Have two separate effects to handle each case.有两个单独的效果来处理每种情况。
Case 1: when the component mounts案例一:当组件挂载时
useEffect(
() => {
// do something
},
[] // no dependency: run once
)
Case 2: when the variable changes案例2:当变量发生变化时
useEffect(
() => {
if (variable) {
// do something
}
},
[variable] // with dependency: run every time variable changes
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.