Why is useState not triggering re-render?

后端 未结 3 1986
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 08:54

I\'ve initialized a state that is an array, and when I update it my component does not re-render. Here is a minimal proof-of-concept:

function App() {
  const         


        
3条回答
  •  不知归路
    2020-12-06 09:43

    You're calling setNumbers and passing it the array it already has. You've changed one of its values but it's still the same array, and I suspect React doesn't see any reason to re-render because state hasn't changed; the new array is the old array.

    One easy way to avoid this is by spreading the array into a new array:

    setNumbers([...old])
    

提交回复
热议问题