[英]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.