如何在 React Native 中对平面列表进行排序? [英] How to sort flatlist in React Native?

查看:65
本文介绍了如何在 React Native 中对平面列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据存储在 flatlist 中显示的状态,我想根据评级对数据进行排序.因此,如果我单击排序按钮,它们应按 升序 顺序排序,当我再次单击时,它们应按 降序 顺序排序.

我有一个存储在 state 中的对象数组,下面只是一段重要的数据.

show_data_list = [{ ratings : { total : 4, ...其他东西 } } ]

有没有办法做到这一点,我尝试使用对数组进行排序的 map 函数

list.map((a,b) => a-b)

但是我如何使用它来对我的对象数组进行排序,我无法传入 2 item.rating.overall 作为参数.

预先感谢您的帮助:)

解决方案

您可以使用 javascript 内置的 sort 函数.你可以为它提供一个自定义的 comparer 函数,如果第一项优先,它应该返回一个负值,如果它们相同,则返回 0,如果第二个值应该优先,则返回正值.>

show_data_list.sort((a, b) => { return a.ratings.overall - b.ratings.overall; }).这将按升序对数据进行排序.

show_data_list.sort((a, b) => { return b.ratings.overall - a.ratings.overall; }).这将按降序对其进行排序.

I have data stored in a state that is shown in flatlist, I want to sort the data based on ratings. So if I click on sort button they should be sorted in ascending order and when I click again, they should be sorted in descending order.

I have an array of objects stored in state, below is just a piece of data that is important.

show_data_list = [{ ratings : { overall : 4, ...other stuff } } ]

Is there a way I could do it, I tried using the map function which sorts array

list.map((a,b) => a-b)

But how can I use this to sort my array of objects, I cant pass in 2 item.rating.overall as the parameter.

Thanks in advance for the help :)

解决方案

You can use javascript's built in sort function. You can provide a custom comparer function for it, which should return a negative value if the first item takes precedence, 0 if they are the same and a positive value if the second value should take precedence.

show_data_list.sort((a, b) => { return a.ratings.overall - b.ratings.overall; }). This will sort the data in the ascending order.

show_data_list.sort((a, b) => { return b.ratings.overall - a.ratings.overall; }). This will sort it in the descending order.

这篇关于如何在 React Native 中对平面列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆