在 useEffect 中,調用更新時是否會更新所有變量? (In useEffect, do all variables get updated when an update is called?)


問題描述

在 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>

Run It Here ...

方法 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 TsabaryJasonbrijesh‑pant)

參考文件

  1. In useEffect, do all variables get updated when an update is called? (CC BY‑SA 2.5/3.0/4.0)

#react-hooks #use-effect #reactjs






相關問題

使用反應鉤子useState更新功能的正確方法是什麼? (What is the correct way to use react hook useState update function?)

測試 react-redux useSelector (testing react-redux useSelector)

從深度嵌套的組件更新狀態而不重新渲染父組件 (Update state from deeply nested component without re-rendering parents)

React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))

類型“IntrinsicAttributes”(自定義掛鉤)上不存在 React 屬性 (React Property does not exist on type 'IntrinsicAttributes' (custom hook))

即使驗證要求無效,數據仍在發送,解決此問題的最佳方法是什麼? (Data is sending even if validation requirements are not valid, whats the best way to approach this?)

如何在使用狀態掛鉤更新狀態時覆蓋具有相同鍵的對象 (How can overwrite objects that have the same key in updating State with state hooks)

在 useEffect 中,調用更新時是否會更新所有變量? (In useEffect, do all variables get updated when an update is called?)

反應鉤子,不會將選中的屬性更改為複選框 (React hooks, does not change the checked property to checkbox)

在 reactJS 中動態設置圖像 src (Setting image src dynamically in reactJS)

如何防止組件在反應中重新渲染? (How to prevent component from re-rendering in react?)

使用 useEffect 和 setInterval 一個接一個地打印一個字母 (print one letter after the other with useEffect and setInterval)







留言討論