【问题标题】:How to go through JSON Array and add Data in to array - react-native如何通过 JSON 数组并将数据添加到数组中 - react-native
【发布时间】:2017-05-16 15:08:07
【问题描述】:

我想将 json 对象添加到数组中。所以我可以将数组添加到我的平面列表组件中。但我不明白如何添加数据数组。

这是我的代码

constructor(props) {
        super(props);
        this.state = {
            Vehicle_Details :[],

        }

var text = JSON.parse(jobs);
                for (var i = 0; i < text.length; i++) {
                    console.log(text[i]["Vehicle_Details"]);
                    this.setState({
                    Vehicle_Details:(text[i])
                    })
                }

但这仅添加了最后一个对象。我该如何解决这个问题?

【问题讨论】:

  • 很明显,因为你正在覆盖它,jobs的内容是什么?
  • 它是我的 json 响应。 ' [{"Vehicle_Details":"Civic","Transmission":"Manual"},{"Vehicle_Details":"fit","Transmission":"Manual"}]'

标签: arrays json reactjs react-native


【解决方案1】:

当您在构造函数本身中解析 JSON 时。无需调用setState,直接赋值即可。

试试这个:

constructor(props) {
  super(props);    

  var text = JSON.parse(jobs);
  this.state = {
    Vehicle_Details: text.map(function(item) {
      return item['Vehicle_Details']
    })
  }
}

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多