React Native - 根据 FlatList 中的另一个 const JSON 过滤 JSON



我正在尝试创建一个平面列表,并根据我获取的JSON和const JSON的值设置左头像图像。我的例子:

const myicons = [
{
title: 'Cotton',
file: require('../assets/images/cotton.png'),
},
{
title: 'Beef',
file: require('../assets/images/beef.png'),
},
];
return (
<View style={{ flex: 1 }}>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<ListItem
leftAvatar={{ source: myicons.filter(myitem => myitem.title === item.product)[0].file }}
title={item.description}
subtitle={`${item.product} ${item.description}`}
/>
)}
keyExtractor={item => item.index}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
</View>
);

当代码如上所示时,我收到 item.product 未定义的错误,而如果我将其硬编码为 myitem.title === 'Beef',它就像一个魅力。接下来的行也适用于项目。

正确的语法是什么?我相信这是最好的方法,但是,如果我没有超过这个,我将不得不在获取的 JSON 中设置文件值,这意味着用户需要更多 KB,我不希望这样。

编辑 我的 this.data.state 值是

[{"date":"Thu, 31 May 2018 00:00:00 GMT","description":"Banana, Europe,($/kg)","index":0,"price":0.96277169112575,"product":"Bananas"},{"date":"Thu, 31 May 2018 00:00:00 GMT","description":"Banana, US,($/kg)","index":1,"price":1.1505360625,"product":"Bananas"},{"date":"Thu, 31 Oct 2019 00:00:00 GMT","description":"Bananas, Central American and Ecuador, FOB U.S. Ports, US$ per metric ton","index":2,"price":1136.5001201057,"product":"Bananas"},{"date":"Wed, 30 May 2018 00:00:00 GMT","description":"Beef - Choice 1","index":3,"price":192.98,"product":"Beef"},{"date":"Wed, 30 May 2018 00:00:00 GMT","description":"Beef - Select 1","index":4,"price":169.31,"product":"Beef"},{"date":"Thu, 31 May 2018 00:00:00 GMT","description":"Beef,($/kg)","index":5,"price":4.15019715,"product":"Beef"},{"date":"Wed, 30 May 2018 00:00:00 GMT","description":"Butter, AA Chicago, lb","index":6,"price":2.425,"product":"Butter"},{"date":"Thu, 31 May 2018 00:00:00 GMT","description":"Cocoa,($/kg)","index":7,"price":2.65994,"product":"Cocoa"},{"date":"Thu, 31 May 2018 00:00:00 GMT","description":"Coffee Price, Arabica, cents/kg","index":8,"price":2.989685182,"product":"Coffee"}]

根据您的代码,传递给平面列表的第一个对象

{
date: "Thu, 31 May 2018 00:00:00 GMT",
description: "Banana, Europe,($/kg)",
index: 0,
price: 0.96277169112575,
product: "Bananas"
}

现在你的过滤函数会喜欢这样

myicons.filter(myitem => myitem.title === 'Bananas')[0].file

但是根据Bananas,您在myicons数组中没有任何值。所以它返回一个undefined.

要修复此错误,请修改myicons以处理所有标题,或提供默认属性以在结果undefined时显示

重要

您可以在JS中使用查找而不是过滤器

myicons.find(myitem => myitem.title === item.product).file

希望这对你有帮助。随意怀疑。

最新更新