問題描述
在 useEffect 中,調用更新時是否會更新所有變量? (In useEffect, do all variables get updated when an update is called?)
如果我有這樣的 useEffect 例如:
useEffect(()=>{
doSomething(varOne, varTwo)
},
[varOne]);
我希望它僅在 varOne 更改時重新運行,但是當它發生時,我希望它具有 varTwo 的更新值出色地。如果 varTwo 發生變化並且沒有發生任何事情,對我來說並不重要,但是當 varOne 發生變化時,它應該在那個時刻使用兩個更新的值運行。
這是我應該期待的嗎?它似乎在我所做的測試中以這種方式工作,但我想確保這是可靠的,以及我應該始終期望它如何工作。
參考解法
方法 1:
Short Answer ... Yes, even if you only reference varOne
in your useEffect
call, all state related values will have already been updated. In the following example, you will see that both varOne
and varTwo
are updated in a button click, but the effect will read both new values when updating the button text.
export default function App() {
const [varOne, setVarOne] = useState('Initial Var One');
const [varTwo, setVarTwo] = useState('Initial Var Two');
const [buttonText, setButtonText] = useState('');
useEffect(() => {
setButtonText(${varOne} ‑ ${varTwo}
)
}, [varOne]);
const handleClick = () => {
setVarOne('Var One Changed');
setVarTwo('Var Two Changed');
}
return (
<div className="App">
<button onClick={handleClick}>{buttonText}</button>
</div>
);
}
</code></pre>
方法 2:
With the functional components, you can also use useRef
equivalent to instance variables in class components. https://reactjs.org/docs/hooks‑faq.html#is‑there‑something‑like‑instance‑variables
(by Tsabary、Jason、brijesh‑pant)
參考文件