首页 > 解决方案 > 如何在本机反应中同时映射两个数组?

问题描述

如何在本机反应中映射两个不同的数组?就我而言,我正在从服务器获取响应并对其进行映射。还有另一个名为的数组images,我想与从服务器获取的响应一起列出。但是第二个映射在第一个映射中循环。我如何将它与第一个分开?以下是我的代码。

示例代码

<ScrollView>
  {this.state.workers.map(a =>
    <CardSection>
      <TouchableOpacity onPress={() => this.popupDialog.show()}>
        <View style={{ marginTop: 10, marginLeft:120}}>
          {images.map(b =>
            <Image
              style={{ height: 100, width: 100 }}
              source={{ uri: b.image }}
             />
           )}
           <Text style={{marginLeft:20, fontSize:20}}>{a.work_type}</Text>
         </View>
       </TouchableOpacity>
     </CardSection>
   )}

workersarray 是我从服务器获取的 json 响应。images数组如下

export const images = [
  {
    image:'http://localhost:3000/Images/carpenter.png',
    text:'hello'
  },
  {
    image:'http://localhost:3000/Images/electrician.png',
    text:'hii'
  },
]

这也是workers数组的样子

更新

 [
        {
            "sl.no": 1,
            "worker_id": "wr_1",
            "work_type": "carpenter",
            "phone_num": "3456789243"
        },
        {
            "sl.no": 2,
            "worker_id": "wr_2",
            "work_type": "electrician",
            "phone_num": "345221344"
        },
        {
            "sl.no": 3,
            "worker_id": "wr_3",
            "work_type": "plumber",
            "phone_num": "8976545677"
        }
    ]

标签: javascriptreact-nativejsxarray-map

解决方案


如果图像未加载,可能是因为您将错误的属性传递给<Image />组件。查找<Image />组件的文档或将其替换为<img />,并将图像的 url 字符串传递给src属性。

getImageUri(worker) {
  // Decide which image to return for a certain type of worker
  // For more workers and images, change the following logic
  if(worker.work_type == 'carpenter') {
    return images[0].image;
  } else if(worker.work_type == 'electrician') {
    return images[1].image;
  } else {
    return '';
  }
}

render() {
...
<ScrollView>
  {this.state.workers.map((a, index) =>
    <CardSection>
      <TouchableOpacity onPress={() => this.popupDialog.show()}>
        <View style={{ marginTop: 10, marginLeft:120}}>
            <Image
              style={{ height: 100, width: 100 }}
              source={{ uri: this.getImageUri(a)}}
             />
           <Text style={{marginLeft:20, fontSize:20}}>{a.work_type}</Text>
         </View>
       </TouchableOpacity>
     </CardSection>
   )}
</ScrollView>
...
}

推荐阅读