gpt4 book ai didi

javascript - 在 React 中对对象数组进行排序并渲染它们

转载 作者:行者123 更新时间:2023-12-03 13:00:10 27 4
gpt4 key购买 nike

我有一个包含一些信息的对象数组。我无法按照我想要的顺序呈现它们,我需要一些帮助。我这样渲染它们:

this.state.data.map(
(item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

是否可以在 map() 函数中使用 item.timeM 对它们进行升序排序,或者我是否必须在使用 map 之前对它们进行排序?

最佳答案

这可能就是您正在寻找的:

// ... rest of code

// copy your state.data to a new array and sort it by itemM in ascending order
// and then map
const myData = [].concat(this.state.data)
.sort((a, b) => a.itemM > b.itemM ? 1 : -1)
.map((item, i) =>
<div key={i}> {item.matchID} {item.timeM}{item.description}</div>
);

// render your data here...

方法排序 will mutate the original array 。因此,我使用 concat 方法创建一个新数组。字段 itemM 上的排序应该适用于可排序的实体,例如字符串和数字。

关于javascript - 在 React 中对对象数组进行排序并渲染它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572436/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com