如何使用ES6在render()中映射Redux中存储的对象数组

时间:2019-03-23 13:05:42

标签: react-native

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),它将为我显示上面的正确数据结构。因此,在映射到呈现的组件时遇到麻烦。

1 个答案:

答案 0 :(得分:0)

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

赞!

    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:

此外,我认为您的错误之一是您在render内部传递了一个函数。修改const测试只是一个正常的组件值

赞:

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

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

现在可以使用。希望对您有帮助:D