loops - React Native:使用数组循环遍历对象数组来创建组件
问题描述
在 React Native(我对 React 很陌生)中,我有一个 javascript 函数,它在一个名为 myResult 的变量中返回一个数组。在终端打印它显示:
Array [
25,
25,
20,
10,
5,
5,
]
我添加到状态
this.setState({resultArray: myResult});
然后,在状态下,我有一个这样的数组:
this.state = {
foodList: [
{id: "25",
src: `"./images/banana25.png"`
},
{id: "20",
src: `"./images/banana20.png"`
},
{id: "15",
src: `"./images/apple15.png"`
},
{id: "10",
src: `"./images/mango10.png"`
},
{id: "5",
src: `"./images/steakNeggs5.png"`
},
}
使用 resultArray 我想在每个项目的视图中显示一个图像,该图像对应于与每个数组项目匹配的 id。
<View style={{height: 318, flexDirection: "row" }}>
{this.state. resultArray.map((item, key) => {
let src = this.state.foodList.item.src
return (
<Image key={key} style={{flexDirection: "row" }} source={require({src})} />
);
})}
</View>
显然,这不起作用,因为我没有适合 src 的语法。
有人可以告诉我从 foodList 数组中获取 src 的正确语法吗?
此外,根据文档,使用索引作为键有效但不赞成,但由于 resultArray 可以(在这种情况下,确实)保存相同的数字/字符串,我认为使用数组项是不可能的。考虑到输出只会产生 1-10 个图像组件,使用 Math.random() 会是一种创建密钥的方法吗?
解决方案
我相信这条线应该是这样的:
<View style={{height: 318, flexDirection: "row" }}>
{this.state.resultArray.map((item, key) => {
let src = this.state.foodList.find(food => +food.id === item).src;
return <Image key={key} style={{flexDirection: "row" }} source={uri: src)} />;
})}
</View>
此外,使用 Math.random 作为键同样不受欢迎。请阅读https://reactjs.org/docs/reconciliation.html
推荐阅读
- mysql - 错误代码:1271. mysql 上操作“UNION”的排序规则的非法混合
- blockchain - 我想在 tron 区块链上的 php 调用智能合约方法函数
- c - 与标志 MEM_RESERVE 一起使用的 VirtualAlloc() 的间接内存消耗
- c++ - 实现散列 ADT 时发生读取访问冲突
- reactjs - 无法删除 create-react-app 的全局安装
- java - 是否可以使用 java 代码从 sql server 管理中检索图像并在 jsp 页面中显示
- python - Python on_reaction_add
- android - 如何在android中处理动态变化的JSON对象
- python - 如何通过pyvisa自定义PXI背板设置?
- javascript - 相互计算两个数组javascript