簡體   English   中英

為什么 React 狀態沒有正確更新?

[英]Why is the React state not being updated properly?

我正在制作一個數學游戲,我希望在完成一定數量的問題后更新操作數的范圍。 我有這個代碼來設置難度

  const [difficulty, setDiff] = useState({rangeA:[1, 10], rangeB:[1, 10]});
  
  function setDifficulty(op) {
    let rangeA = [];
    let rangeB = [];
    if (question < 5) { //question state is incremented everytime the answer is correct, which triggers the next question
      rangeA = [0, 100];
      rangeB = [0, 10];
    }
    else if (question < 8) {
      rangeA = [0, 100];
      rangeB = [0, 100];
    }
    setDiff({...difficulty, rangeA, rangeB});
    console.log(rangeB, difficulty.rangeB); // when question is 5, this logs [0, 100] [0, 10], but they should be the same value [0,100]
  }

但是狀態沒有正確更新,會發生什么?

在 React 中設置狀態就像一個異步函數。
這意味着當您設置狀態並在其后放置一個console.log時,它可能會在狀態實際完成更新之前運行。

這就是我們使用useEffect的原因,這是一個內置的 React 鈎子,當其中一個依賴項發生更改時,它會激活回調。

例子:

useEffect(() => {
   console.log(difficulty)
   // Whatever else we want to do after the state has been updated.
}, [difficulty])

console.log將僅在狀態更改完成並發生渲染后運行。

  • 注意:示例中的“難度”可以與您正在處理的任何其他狀態部分互換。

查看文檔以獲取更多信息。

當您調用setDiff時,新的difficulty值將在下一次渲染期間更新。 由於您是setDifficulty函數中的console.log ,因此在渲染發生之前,對difficulty.rangeB的引用仍然保持更新前的值。

暫無
暫無

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

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