簡體   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