簡體   English   中英

如何在 React 中對對象內部的數組進行排序?

[英]How to sort array inside object in 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);

我嘗試在函數中使用這種排序並更改狀態

問題

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM