简体   繁体   English

反应 setState() 不触发重新渲染

[英]react setState() not triggering re-render

I have component which receives data from other file and setting into state:我有一个从其他文件接收数据并设置为 state 的组件:

const [sortedPlans, setSortedPlans] = useState(
    data.Plans.sort((a, b) => b.IndustryGrade - a.IndustryGrade)
  );//data is from external file

After setting the state, sorting the data and rendering the initial screen, I have function that sorts the sortedPlans whenever it is called:设置 state、排序数据并呈现初始屏幕后,我有 function 每当调用 sortedPlans 时对其进行排序:

const sort = (event) => {
    console.log(event);
    const newArr = sortedPlans.sort((a, b) => {
      return b[event] - a[event];
    });
    console.log(newArr);
    return setSortedPlans(newArr);
  };

The problem is that this is never triggering a re-render of the component.问题是这永远不会触发组件的重新渲染。 I want when I set the new state to be able to see it inside the jsx.我希望当我设置新的 state 时能够在 jsx 中看到它。 Why when I console.log(newArr) the results are correctly sorted but this setting of the state not triggering re-render?为什么当我使用 console.log(newArr) 结果排序正确,但 state 的设置没有触发重新渲染? Here is the sandbox:这是沙箱:

https://codesandbox.io/s/charming-shape-r9ps3p?file=/src/App.js https://codesandbox.io/s/charming-shape-r9ps3p?file=/src/App.js

Here you go: Codesandbox demo .给你 go: Codesandbox 演示

You should first make a shallow copy of the array you want to modify.您应该首先对要修改的数组进行浅表复制。 Then set that array as the new state. Then it re-renders the component and you are able to filter like you want.然后将该数组设置为新的 state。然后它会重新呈现组件,您就可以按照自己的意愿进行过滤。

  const sort = (event) => {
    console.log(event);
    //shallow copying the state. 
    const newArr = [...sortedPlans];

    //modifying the copy
    newArr.sort((a, b) => {
      return b[event] - a[event];
    });
    console.log(newArr); //results here are correctly sorted as per event
    
    //setting the state to the copy triggers the re-render.
    return setSortedPlans(newArr);
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM