[英]How to avoid rendering items with same id in the flatList multiple times?
我从 api 得到奇怪的数据。
数据是这样的
const dataArray = [
{ id: "PROD7", color: "green", weight: 2, price: 300 },
{ id: "PROD7", color: "red", weight: 2, price: 300 },
{ id: "PROD11", color: "cyan", weight: 4, price: 450 },
{ id: "PROD7", color: "yellow", weight: 2, price: 300 },
{ id: "PROD7", color: "blue", weight: 2, price: 300 },
];
如您所见,相同的id
多次出现。 这是产品列表 api。 我有一个最喜欢的名单。 哪个用户设置为最爱。
const myFavIds = ["PROD7"];
我现在正在做的是尝试渲染myFavoriteList
组件,因此我从dataArray
获取数据并检查myFavIds
是否包含在dataArray
中。
如果包括在内,我将渲染 api。 但问题是我得到了multiple same id
所以我想避免渲染相同的 id twice or thrice...
我使用的是flatList
来渲染组件。 无论如何要检查 id 以及在以前的情况下是否有相同的 id。 躲开它。
这是我渲染 flatList 的方式
<FlatList
data={dataArray}
renderItem={renderItem}
keyExtractor={(item, index) => String(index)}
/>
const renderItem = ({item, index}) => {
if (favList.includes(item.id)) {
return (
<IndividualProduct
info={item}
index={index}
key={index}
fav={true}
stateChange={stateChange}
setLoading={setLoading}
/>
);
}
};
理想情况下,您的 API 不应为您提供具有误导性的数据。 与您的后端 API 开发人员交谈以解决此问题。
回到您的问题,您可以通过使用LODASH uniqBy
function 来避免您的问题。 例如,在你的情况下打电话。
var filteredArray = _.uniqBy(dataArray, 'id');
这将为您提供一个只有唯一 id 值的过滤数组。 现在将其传递给您的平面列表并执行您的流程的 rest。
任何“ID”都应该不同且唯一。 查看您的数据,同一个 ID 有不同的值。 如果您可以考虑丢失数据,则可以过滤数组以仅包含唯一元素:
const dataArray = [ { id: "PROD7", color: "green", weight: 2, price: 300 }, { id: "PROD7", color: "red", weight: 2, price: 300 }, { id: "PROD11", color: "cyan", weight: 4, price: 450 }, { id: "PROD7", color: "yellow", weight: 2, price: 300 }, { id: "PROD7", color: "blue", weight: 2, price: 300 }, ]; const uniqueArray = dataArray.filter(({ id }, i, _arr) => _arr.findIndex((elem) => elem.id === id ) === i); console.log(uniqueArray);
并将uniqueArray
作为道具传递。
<FlatList
data={uniqueArray}
renderItem={renderItem}
keyExtractor={(item, index) => String(index)}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.