Why is useState not triggering re-render?

后端 未结 3 1980
没有蜡笔的小新
没有蜡笔的小新 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:35

    Others have already given the technical solution. To anyone confused as to why this happens, is because setSomething() only re renders the component if and only if the previous and current state is different. Since arrays in javascript are reference types, if you edit an item of an array in js, it still doesn't change the reference to the original array. In js's eyes, these two arrays are the same, even though the original content inside those arrays are different. That's why setSomething() fails do detect the changes made to the old array.

    Note that if you use class components and update the state using setState() then the component will always update regardless of whether the state has changed or not. So, you can change your functional component to a class component as a solution. Or follow the answers provided by others.

提交回复
热议问题