javascript - 如何在 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);
我尝试在函数中使用这种排序并更改状态
解决方案
问题
array.prototype.sort
是一种就地排序,这意味着它只会改变状态。你不应该直接操纵状态(即this.state.data
)。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)
}));
};
如果您的意思是要对点而不是数据进行排序,则过程类似。复制每个级别的状态,然后通过排序复制要更新的数组。
sortPoints = () => {
this.setState((state) => ({
...state,
data: state.data.map((dataItem) => ({
...dataItem,
points: dataItem.points.slice().sort((a, b) => a.x - b.x)
}))
}));
};
推荐阅读
- vb.net - 如何删除 DatagridView 和 Ms Access 中的选定行
- url - 有没有办法创建一个路由到各种 YouTube 流 URL 的 URL?
- sharepoint - 使用 Graph API 在 SharePoint 网站中搜索匹配的文件夹名称
- node.js - 无法根据 TypeOrm 中的外键过滤数据
- java - 记录视图不显示
- can-bus - 如何通过 CAPL 脚本处理接收 CAN 帧中的数据并将其转发到同一 CAN 总线?
- flutter - 使用 Theme 小部件设置 CircularProgressIndicator 的 backgroundColor
- java - @JsonProperty 存在但返回 null
- kubernetes - kubectl create configmap - 使用 --file-name 选项生成时从输出配置映射中删除文件名的选项
- atmelstudio - 使用 Atmel Studio 时进入编程模式时出现问题