reactjs - React Native 中的客户映射
问题描述
我有一个数组状态,我试图将它映射到一个组件中,其中每三个项目进入一个道具。该数组包含以下内容:
players: [1, "Timmy", "H", 2, "Julie", "M"]
这是我映射它的方式:
const myPlayers = this.state.players.map((id, first, last) =>
<Player
key={id}
fName={first}
lName={last}
/>
)
基本上,数组的 0,3,6,9... 项是索引 1,4,7,10... 数组的项是名字 2,5,8,11... 项的数组是姓氏
当我尝试将它映射到上面代码片段中提到的组件时,我在屏幕上得到了这个结果:
0 1TimmyH2JulieM
1 1TimmyH2JulieM
2 1TimmyH2JulieM
3 1TimmyH2JulieM
4 1TimmyH2JulieM
5 1TimmyH2JulieM
我希望得到的结果是:
Timmy H
Julie M
这是我的播放器组件的代码片段以供参考:
<TouchableOpacity>
<View style={styles.container}>
<Text style={styles.name}>{props.fName} {props.lName}</Text>
</View>
</TouchableOpacity>
知道如何实现这一目标吗?谢谢
解决方案
This is not how map works. Map applies the function to every element of the array. You cannot group them. What I suggest you to do is to have a structure like this:
players: [{id:1, firstName:"Timmy", lastName:"H"}, {id:2, firstName:"Julie", lastName:"M"}]
. This way your map will work, plus is much easier to deal with operations like push or remove and other programmer can easily understand your code.
If you still want to keep that structure you should use a for instead of map.
推荐阅读
- nosql - Vespa 与其他无 SQL 数据库
- php - 如何提供一个文件夹来从 Web 应用程序写入和下载临时文件?
- configuration - traefik.toml 中的后端和前端是什么
- c++ - I get the Assertion failure "file_name != nullptr" but only in release mode
- asp.net-mvc - 在 FireFox 版本 64 上的时刻 DateTime 格式(额外 -)不正确
- css - 如何命名仅包含 @import 语句的 Sass 文件
- mysql - 足球队实体关系图
- sql - 查询小于特定时间的时间
- ffmpeg - FFMPEG 没有记录整个窗口
- python - requests.post is not giving any response in python?