简体   繁体   English

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

[英]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]);

I've solved this problem many times using a ref我已经多次使用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