reactjs - React Native,映射 JSON
问题描述
我无法弄清楚如何在 React Native 中正确映射这个 JSON。我需要重写这个json吗?
这是json
"rewards" : {
"0" : {
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
},
"1" : {
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
},
{...}
这是我尝试映射的内容
renderItems(){
const{rewards} = this.props;
return rewards.map((data, i) => {
return (<Text> {data[i].name} </Text>)
})
}
解决方案
是的,您需要重写 JSON,因为map()期望奖励是一个对象数组。例如:
{
"rewards": [{
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
},
{
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
}]
}
如果您还没有,您还需要在奖励道具上使用JSON.parse 。下面是一个示例,说明在使用奖励属性渲染组件时如何使用 JSON.parse:
render() {
const rewardsJSON = '{"rewards":[{"entries":0,"image":"url","name":"PlayStation 4 Pro 1TB Console","url":"","price":399.99},{"entries":0,"image":"url","name":"Xbox One S 500GB","url":"","price":249.99}]}';
return (
<YOUR_COMPONENT
rewards=JSON.parse(rewardsJSON).rewards
/>
);
}
推荐阅读
- javascript - 如何根据纵向或横向模式(和方向更改)更改“初始比例”?
- javascript - 如果我将函数分配给变量,则会在控制台中显示错误
- typescript - 如何使用打字稿和玩笑模拟猫鼬模式,使用什么类型返回?
- c++ - 为包含多个 QQuickPaintedItems 的 QQuickView 实现滚动
- api - Bandcamp api:查询 my_bands 端点时,您发送什么 POST 信息?
- linux - 如何从源代码构建 Guile 库?
- python - 使用python从netCDF文件中提取数据
- android - 版本更新后我的 Android 电子邮件代码损坏
- javascript - 当我单击其中的任何位置时,如何阻止我的模态关闭
- ios - iOS本机媒体控制器名称?