react-native - 如何使用 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) 它会向我显示上面的正确数据结构。所以只是无法映射到渲染的组件。
解决方案
尝试将您的数据结构更改为数组,
像这样:
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
推荐阅读
- html - td 内的表 100% 高度不占用外表的高度
- php - 如何使用静态库为 PHP 创建用 C++ 编写的扩展
- pentaho - pentaho - 从一个转换共享到另一个转换
- json - 如何使用 jq 反转地图并为重复值创建列表?
- javascript - 通过使用嵌套数组循环遍历对象数组来创建对象。Javascript
- python - 如何使用 Python 读取数字并跳过字母
- ubuntu - 设置 VSFTPD 用户对 apache2 的 html 目录具有写入权限
- javascript - 是否可以在不阻塞其他脚本的情况下延迟脚本的执行?
- google-chrome - 我的谷歌扩展程序无法打开并卡住
- wordpress - WordPress 504 网关超时与 WooCommerce