在React中对对象数组进行排序并渲染它们
我有一个包含一些信息的对象数组。我无法按照我想要的顺序进行渲染,因此我需要一些帮助。我这样渲染它们:
this.state.data.map(    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)
是否可以item.timeM在该map()功能中对它们进行升序排序,或者我必须在使用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...
该方法sort
将变异原始数组。因此,我使用该concat方法创建了一个新数组。字段itemM上的排序应适用于可排序的实体,例如字符串和数字。
以上是 在React中对对象数组进行排序并渲染它们 的全部内容, 来源链接: utcz.com/qa/431905.html








