我有一个 React 对象数组,我想根据其中一个 props 的值对它们进行排序。
var arr=[];
arr[0] = <Fruit name="orange" count={10}/>
arr[1] = <Fruit name"apple" count={5}/>
是否有内置的 React 函数,我可以使用它按水果 count
的升序对这个数组进行排序?
最佳答案
React 没有内置函数来处理这个问题(据我所知),但你可以使用类似 lodash 的函数。实现你想要的。我还建议您稍微更改数据结构。请看下面的示例。
// your data comes in like this
var arr = [
{name: "orange", count: 10},
{name: "apple", count: 5},
{name: "lemon", count: 11},
{name: "grape", count: 2}
];
// order by ascending
var newArr = _.sortBy(arr, 'count', function(n) {
return Math.sin(n);
});
// create your components
var fruits = newArr.map(function(fruit) {
return(
<Fruit name={fruit.name} count={fruit.count} />
);
});
Here是一个 fiddle 来说明排序函数的输入输出
关于javascript - ReactJS:如何根据 Prop 的值(value)对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32861889/