React/react hooks: child component is not re-rendering after the state is changed?

后端 未结 3 1117
灰色年华
灰色年华 2021-01-25 22:29

I am writing a code in react/react hooks that attempt to do the following.

Get an array of objects from the parent component as a prop Set it as a state using useS

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 23:08

    React checks for changes in props and state by doing a shallow object equality check. If you set the state to the same object you received from state, React assumes you aborted your change and doesn't do anything, even if the properties on the object changed.

    The key is that the sort() method sorts the array in place, and returns a reference to the same array. So React sees it as the same array object, even though the orser of its entries is different.

    The solution is to create a new array:

    let k = [...newarray];
    

    When k is passed to setnewarray, React sees that it is an entirely different object, and triggers the rerender.

提交回复
热议问题