首页 > 解决方案 > 如何使用 ES6 在 render() 中映射存储在 Redux 中的对象数组

问题描述

RN 新手并试图理解对象映射。我似乎无法在我的应用程序中获得与此类似的 StackO 答案。我会得到 this.props.locations 是未定义的,所以我用你在下面的数据结构中看到的对象“latlons”初始化了对象。

this.props.locations

{
  "latlons": {
    "latitude": "0",
    "longitude": "0",
    "accuracy": "0"
  },
  "0": {
    "latitude": 37.33382825,
    "longitude": -122.07735141,
    "accuracy": 5
  },
  "1": {
    "latitude": 37.35304318,
    "longitude": -122.1073468,
    "accuracy": 5
  },
  "2": {
    "latitude": 37.37664016,
    "longitude": -122.14817958,
    "accuracy": 5
  },
  "3": {
    "latitude": 37.38885423,
    "longitude": -122.15958014,
    "accuracy": 5
  },
  "4": {
    "latitude": 37.40479565,
    "longitude": -122.1870328,
    "accuracy": 5
  },
  "5": {
    "latitude": 37.412672,
    "longitude": -122.20550149,
    "accuracy": 5
  }
}

当我使用 RN 0.59.1 和 React 16.8 时,我尝试了:

   render() {
     const Test = ({locations}) => (
       <>
         {this.props.locations.map(locations => (
           <Text> key={locations.latitude} {locations.longitude}</Text>
         ))}
       </>
     );

     return (
       <View style={styles.container}>
         <View>
          {Test}
         </View>
       </View>
     );
   }

但它不会在视图中打印任何内容。做错了什么?

编辑:我确实正确配置了 Redux,因为如果我 console.log(this.props.locations) 它会向我显示上面的正确数据结构。所以只是无法映射到渲染的组件。

标签: react-native

解决方案


尝试将您的数据结构更改为数组,

像这样:

    example = [
   {
    "latitude": "0",
    "longitude": "0",
    "accuracy": "0"
  },
  {
    "latitude": 37.33382825,
    "longitude": -122.07735141,
    "accuracy": 5
  },
  {
    "latitude": 37.35304318,
    "longitude": -122.1073468,
    "accuracy": 5
  },
   {
    "latitude": 37.37664016,
    "longitude": -122.14817958,
    "accuracy": 5
  },
  {
    "latitude": 37.38885423,
    "longitude": -122.15958014,
    "accuracy": 5
  },
  {
    "latitude": 37.40479565,
    "longitude": -122.1870328,
    "accuracy": 5
  },
  {
    "latitude": 37.412672,
    "longitude": -122.20550149,
    "accuracy": 5
  }
]

编辑1:

另外我认为你的一个错误是你在渲染中传递了一个函数。修改你的 const 测试只是一个正常的组件值

像这样:

 render() {
  const Test = (
    <>
      {sample.map(locations => (
        <Text> key={locations.latitude} {locations.longitude}</Text>
      ))}
    </>
  );

  return (
    <View style={styles.container}>
      <View>
       {Test}
      </View>
    </View>
  );
}
}

它现在可以工作了。希望它有所帮助:D


推荐阅读