首页 > 解决方案 > 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() 会是一种创建密钥的方法吗?

标签: loopsreact-nativejsx

解决方案


我相信这条线应该是这样的:

<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


推荐阅读