我在弄清楚如何在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>)
})
}
答案 0 :(得分:0)
是的,您需要重写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(如果尚未使用)。这是一个示例,说明在使用rewards prop渲染组件时如何使用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
/>
);
}
答案 1 :(得分:0)
.map()
应该在数组上调用。 rewards
此处不是数组,因此一种解决方案是先将其转换为数组。
假设您的json是这样:
const myJson =
{
"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
}
}
您可以将其(任意长度)动态转换为数组:
let index = 0
let dataArr = []
while (myJson.rewards[index]) {
arr.push(myJson.rewards[index])
index++
}
跳过上面的代码已经足够清楚了...
因此,dataArr
现在包含如下数据:
dataArr = [{
"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 dataArr.map((data, i) => (<Text key={i}> {data.name} </Text>))