首页 > 解决方案 > 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>)
  })
}

标签: reactjsreact-native

解决方案


是的,您需要重写 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 
    />
  );
}

推荐阅读