【问题标题】:Sort the obj in array By React useEffect method通过 React useEffect 方法对数组中的 obj 进行排序
【发布时间】:2020-07-20 10:05:11
【问题描述】:

我在这里只粘贴了我的部分 React 代码,我的 State 中有一个数组,它可以更新并从浏览器添加新数组。

我的问题是我希望数组可以按时间值从小到大排序并输出到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?”}
]);

【问题讨论】:

    标签: reactjs sorting use-effect arrayobject


    【解决方案1】:

    您可以使用useMemo,它只会在rows 更改时对数组进行排序

    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);
    

    但在大多数情况下,反应非常快,您可以在每次渲染时对数组进行排序,而不必担心性能

    const sorted = rows.slice().sort((a, b) => a.time - b.time);
    

    【讨论】:

      【解决方案2】:

      您可以使用useEffect 并在其依赖项数组中添加rows,这样它就会在行更新时进行监视。 有两种方法可以实现:

      1. 创建一个新的状态变量来保存排序后的数组
      const [sortedRows, setSortedRows] = useState([])
      useEffect(() => {
        const _sortedRows = [...rows].sort((a, b) => a.time - b.time); // as sort mutates the array, thats why created new array through spread operator
        setSortedRows(_sortedRows);
      }, [rows])
      
      1. 使用useMemo钩子:
      const sortedRows = React.useMemo(() => [...rows].sort((a, b) => a.time - b.time), [rows])
      

      【讨论】:

      • 获得无限渲染,因为setRows 设置新数组rowsuseEffect 调用,因为rows 改变了:)
      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多