簡體   English   中英

在反應鈎子中更新 state

[英]Updating state in react hooks

1.

const [count, setCount] = useState(0);

setCount(count+1);

或者

2.

const [count, setCount] = useState(0);

setCount(count => count+1);

我很困惑何時應該在我的組件中使用兩種更新 state 的方法,它有什么區別? 謝謝。

當新的 state 獨立於以前的 state 時,使用選項 1,例如從服務器獲取數據並且您只是替換當前的 state。

當下一個 state取決於當前 state 時,使用選項 2,例如遞增計數。

順便說一句,選項 2 的模式稱為功能更新,因為您將其傳遞給純 function,它采用當前的 state,對其進行變異,然后返回下一個 Z9ED39E2EA931586B6A985A6942EF53。

以下是我創建的一個計數演示,以真正展示兩者之間的區別以及為什么區別很重要。

const [count, setCount] = useState(0);

/**
  * count +3 click handler using naive state updates.
  */
const clickHandler1 = () => {
  // assume count equals some number n
  setCount(count + 1); // update queued, count === n, count = n + 1
  setCount(count + 1); // update queued, count === n, count = n + 1
  setCount(count + 1); // update queued, count === n, count = n + 1
  // when processed the count will be n + 1
};

/**
  * count +3 click handler using functional state updates.
  */
const clickHandler2 = () => {
  // assume count equals some number n
  setCount(count => count + 1); // update queued, count === n + 0, count = prevCount + 1
  setCount(count => count + 1); // update queued, count === n + 1, count = prevCount + 1
  setCount(count => count + 1); // update queued, count === n + 2, count = prevCount + 1
  // now when processed each call uses the result of the previous update
  // count will be n + 1 + 1 + 1, or n + 3
};

編輯反應 - 壞和好的狀態更新

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM