首页 > 解决方案 > 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>

知道如何实现这一目标吗?谢谢

标签: reactjsreact-native

解决方案


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.


推荐阅读