[英]React hook only when props change?
useEffect(() => {
// do something
}, [stringProp]);
stringProp
is by default an empty string. stringProp
默认为空字符串。
When I change stringProp
to foobar
the effect runs.当我将stringProp
更改为foobar
时,效果会运行。
But,但,
the useEffect
also runs when the component first mounts, which I don't want. useEffect
也会在组件首次安装时运行,这是我不想要的。
How to run an effect hook ONLY when props change?仅当道具更改时如何运行效果挂钩?
You can not stop useEffect
run when the component first mounted, but you can do the condition checking to run your code inside it like this:您不能在组件首次安装时停止useEffect
运行,但您可以进行条件检查以在其中运行您的代码,如下所示:
useEffect(() => {
// Only run when stringProp has value, you might have different condition, add them there
if(stringProp){
// do something
}
}, [stringProp]);
Updated: If you might set stringProp back to the initial value, you can do use useRef
to control first time run like this更新:如果您可能将 stringProp 设置回初始值,您可以使用useRef
来控制第一次运行,如下所示
const isFirstTimeOfUseEffect = useRef(true)
useEffect(() => {
// Only run when stringProp has value, you might have different condition, add them there
if(!firstUseEffectRun.current){
// do something
}else{
firstUseEffectRun.current = false
}
}, [stringProp]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.