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

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

    Sort() work in place, which means you won't get what you want via directly return.

    By the way, you can write the sort() in a better format as below

    const otc = () => {
      const result = [...newarray];
      result.sort((a, b) => b.time - a.time);
      setNewarray(result);
    };
    const orc = () => {
      const result = [...newarray];
      result.sort((a, b) =>
        a.rating !== b.rating ? b.rating - a.rating : b.time - a.time
      );
      setNewarray(result);
    };
    

    Try it online here:

提交回复
热议问题