繁体   English   中英

仅在道具更改时才反应钩子?

[英]React hook only when props change?

useEffect(() => {
  // do something
}, [stringProp]);

stringProp默认为空字符串。

当我将stringProp更改为foobar时,效果会运行。

但,

useEffect也会在组件首次安装时运行,这是我不想要的。

仅当道具更改时如何运行效果挂钩?

您不能在组件首次安装时停止useEffect运行,但您可以进行条件检查以在其中运行您的代码,如下所示:

useEffect(() => {
  // Only run when stringProp has value, you might have different condition, add them there
  if(stringProp){
    // do something
  }
}, [stringProp]);

更新:如果您可能将 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]);

我已经多次使用ref解决了这个问题

const firstRun = useRef(true);
...
useEffect(() => {
  // skip the first run
  if (firstRun.current) {
    firstRun.current = false;
    return;
  }

  // do stuff
}, [stringProp]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM