[英]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.