在React中对对象数组进行排序并渲染它们 [英] Sort an array of objects in React and render them
本文介绍了在React中对对象数组进行排序并渲染它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含一些信息的对象数组。我无法按照我想要的顺序渲染它们,我需要一些帮助。我这样渲染它们:
I have an array of objects containing some information. I am not able to render them in the order I want and I need some help with that. I render them like this:
this.state.data.map(
(item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)
是否可以在 map()中使用
item.timeM
对它们进行升序排序/ code> -function还是我必须在使用map之前对它们进行排序?
Is it possible to sort them ascending with item.timeM
in that map()
-function or do I have to sort them before i use map?
推荐答案
这可能就是你要找的东西:
This might be what you're looking for:
// ... 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)
.map((item, i) =>
<div key={i}> {item.matchID} {item.timeM}{item.description}</div>
);
// render your data here...
方法 sort
会改变原始数组。因此,我使用 concat
方法创建一个新数组。
The method sort
will mutate the original array . Hence I create a new array using the concat
method.
这篇关于在React中对对象数组进行排序并渲染它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文