2017-06-18 40 views
-2

我已经设置了名为data的状态并将其声明为getInitialState()中的空数组。此外,我已经做了一个Ajax调用,并获得了componentDidMount()中返回的JSON。如何使用React中的setState将多个JSON请求推送到数组中

如何使用setState方法将多个JSON请求推送到称为数据的数据?

var Forecast = React.createClass({ 

    getInitialState() { 
     return { 
      data: [] 
     } 
    }, 

    componentDidMount: function() { 
     this.serverRequest = $.get('http://api.openweathermap.org/data/2.5/weather?zip=3000,au&appid=005fa98ae858a29acf836ecdefac0411', function(result) { 
      var tempData = result; 
      this.setState({ 
       // Is there any way to push multiple JSON into an array? 
       // below line of code is my attempt 
       data: tempData 
      }); 
     }.bind(this)); 
    } 

    ... 
} 
+0

'data [0]'是未定义的,因为数组是空的。不知道ajax调用,你确定结果是一个数组吗? – webdeb

回答

1

我敢肯定的jQuery不会自动转换为数组为您提供:

this.serverRequest = $.get('http://api.openweathermap.org/data/2.5/weather?zip=3000,au&appid=005fa98ae858a29acf836ecdefac0411', function(result) { 
    var tempData = JSON.parse(result); 
    this.setState({ 
     data: tempData // reset the data 
    }); 
}.bind(this)); 

东西之类的将工作

编辑:您没有按照协议的API。我手动键入它到浏览器中,并得到了这样的结果:

{"coord":{"lon":144.96,"lat":-37.81},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":283.48,"pressure":1032,"humidity":76,"temp_min":282.15,"temp_max":285.15},"visibility":10000,"wind":{"speed":4.6,"deg":360},"clouds":{"all":75},"dt":1497828600,"sys":{"type":1,"id":8201,"message":0.0048,"country":"AU","sunrise":1497821707,"sunset":1497856068},"id":0,"name":"Melbourne","cod":200} 

这显然不是一个数组(所以你不能说data[0]

如果您要访问的JSON对象只是去,如:

console.log(data["coord"]); // this will return {"lon":144.96,"lat":-37.81}

编辑:如果你想存储请求的列表,你需要这样做:

this.setState({ 
    data: this.state.data.concat(tempData) 
}) 
+0

谢谢,我编辑了我的代码,以便状态可以容纳一个对象。有没有办法使用setState()将对象推入数组?我想保持状态为一个数组。 – Hooey

+0

@霍伊好吧,我明白你的意思了。请加上这个问题 – AJC

+0

谢谢。我刚刚加入我的问题 – Hooey

0

看来你是从'api.openweathermap.org'获得的响应作为普通的JavaScript对象而不是数组。所以你必须相应地改变你的初始状态和console.logrender方法。

getInitialState() { 
    return { 
     data: null 
    } 
} 

render() { 
    console.log(this.state.data); 
    //... 
}) 

如果你想要把你的回应到data数组中的状态,使用concat

this.setState({ 
    data: this.state.data.concat([tempData]) 
}); 
0

所以,你想把返回的对象放入数组中,添加它?

这个怎么样:

... 
this.setState({ 
    data: this.state.data.concat(tempData) 
}); 

你也可以把它推到state.data阵,但后来多了一个步骤是必需的:

this.state.data.push(tempData); 
this.setState({ 
    data: this.state.data 
}); 

而且这将意味着,修改状态,这不是一个好的做法。对于这个例子,它可能没问题,但这不是一个好习惯。

+0

是的。它不是一个数组,而是一个json对象。我有一个状态是一个数组。我的目标是在我的代码中使用上面定义的setState()将对象放入数组中。 – Hooey

+0

aaa,请参阅我的编辑@Hooey – webdeb

相关问题