我只在这里粘贴了我的React代码的一部分,我的状态中有一个数组,它可以从浏览器更新并添加新数组。
我的问题是我希望数组可以按时间值从小到大排序并输出到console.log,当数组更新时,如何通过useEffect方法使其正确排序?
数组结构就像下面的代码,其他部分只是控制 UI 更新我没有发布在那里,因为这些部分不影响排序功能。
const [rows, setRows] = useState([
{time: 3, msg:”there is the first msg”},
{time: 6, msg:”2nd msg”},
{time:11, msg:”do you have any question?”}
]);
最佳答案
您可以使用useMemo仅当行数更改时才会对数组进行排序
const [rows, setRows] = React.useState([
{ time: 3, msg: 'there is the first msg' },
{ time: 6, msg: '2nd msg' },
{ time: 11, msg: 'do you have any question?' },
]);
const sorted = React.useMemo(() => rows.slice().sort((a, b) => a.time - b.time), [rows]);
console.log(sorted);
但在大多数情况下, react 速度非常快,您可以在每次渲染时对数组进行排序,而不必担心性能
const sorted = rows.slice().sort((a, b) => a.time - b.time);
关于reactjs - 通过 React useEffect 方法对数组中的 obj 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62993051/