React Native-基于FlatList中的另一个常量JSON筛选JSON
我正在尝试创建一个平面列表,并根据获取的JSON和常量JSON的值设置leftAvatar图像。我的例子是:React Native-基于FlatList中的另一个常量JSON筛选JSON,json,react-native,jsx,react-native-flatlist,Json,React Native,Jsx,React Native Flatlist,我正在尝试创建一个平面列表,并根据获取的JSON和常量JSON的值设置leftAvatar图像。我的例子是: const myicons = [ { title: 'Cotton', file: require('../assets/images/cotton.png'), }, { title: 'Beef', file: requ
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>
);
根据您的代码,传递到flatlist的第一个对象
{
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
但是根据香蕉
,在myicons
数组中没有任何值。因此它返回一个未定义的
要修复此错误,请修改myicons
以处理所有标题,或提供默认属性,以便在结果为未定义时显示
重要
您可以在JS中使用find而不是filter
myicons.find(myitem => myitem.title === item.product).file
希望这对你有帮助。请不要怀疑。您可以分享您的this.state.data
值吗。谢谢你的时间,你说得对!这是产品末尾的“s”错误。非常感谢你!
myicons.find(myitem => myitem.title === item.product).file