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

后端 未结 3 1151
灰色年华
灰色年华 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

    array::sort

    The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

    What this means for you is the order of elements stored in an array may change, but the array is sorted in place which means the same array reference is returned (unlike other array functions that return new arrays).

    React reconciliation occurs by examining state and props and makes a holistic assumption that if the next state/prop references haven't changed then the values haven't changed and thus returns the last computed rendered DOM. This is the important detail of updating react state... each update needs to reference a new object.

    In your case you are merely saving the reference to the current array in state, mutating it, and resaving it. Since the reference is stable and doesn't change, react doesn't re-render.

    const otc = () => {
      let k = newarray; // <-- saved array reference!!
      setnewarray(k.sort((a, b) => (a.time > b.time) ? -1 : 1 ));
    }
    

    The correct react way is to copy the current array values into a new array so it will have a new object reference.

    const otc = () => {
      const newSortedArray = [...newArray].sort(
        (a, b) => (a.time > b.time) ? -1 : 1
      ); // spread old array values into new array, then sort
      setNewArray(newSortedArray);
    }
    

提交回复
热议问题