首页 > 解决方案 > 如何在 React 中对对象内部的数组进行排序?

问题描述

如何在另一个处于状态的对象内的 x 值之后对数组进行排序?我正在尝试对“点”数组进行排序

 state = {
        data: [
          {                                 
            color: "black", 
            points: [{x: 61, y: 54}, {x: 182, y: 49}, {x: 37, y: 35},
                     {x: 182, y: 61},{x: 13, y: 73},{x: 173, y: 59}]
        }],
    };

这不起作用:

this.state.data.sort((a, b) => (a.points[0] > b.points[0]) ? 1 : -1);

我尝试在函数中使用这种排序并更改状态

标签: javascriptreactjssorting

解决方案


问题

  1. array.prototype.sort是一种就地排序,这意味着它只会改变状态。你不应该直接操纵状态(即this.state.data)。
  2. points数组元素也是对象,所以不能直接比较,但可以使用它们的属性。

解决方案

您应该使用功能状态更新和浅拷贝您打算更新的状态对象的每个级别。

sortData = () => {
  this.setState((state) => ({
    ...state, // <-- copy existing state
    // slice the existing data array to copy it, then call sort
    // access the `x` property of the first point object
    data: state.data.slice().sort((a, b) => a.points[0].x - b.points[0].x)
  }));
};

编辑 how-to-sort-array-inside-object-in-react

如果您的意思是要对点而不是数据进行排序,则过程类似。复制每个级别的状态,然后通过排序复制要更新的数组。

sortPoints = () => {
  this.setState((state) => ({
    ...state,
    data: state.data.map((dataItem) => ({
      ...dataItem,
      points: dataItem.points.slice().sort((a, b) => a.x - b.x)
    }))
  }));
};

推荐阅读