【发布时间】:2015-12-30 02:56:58
【问题描述】:
鉴于Open Weather Map current weather data API,我正在尝试使用 ajax 将当前天气数据拉入我的 React.js 应用程序,提取给定城市的当前温度值,然后在我的组件中呈现该值。
我正在使用的测试 JSON 数据位于以下网址: http://api.openweathermap.org/data/2.5/weather?id=5391997&units=imperial
var CityGrid = React.createClass({
componentDidMount: function() {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?id=5391997',
// ^^ this should get a variable where id=5391997 is set
dataType: 'json',
success: function(data) {
this.setState({temp: data.main.temp});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState:function(){
return{
cities:[
{
name: "San Francisco",
id: 5391997,
temp: 50, // << this should receive value from ajax call
UTCOffset:-7,
address: 999 Nathan Lane,
phone: 555-5555
},
// 12 more city objects in this array, removed for brevity
]}
},
render: function() {
console.log(this.state.temp); // << this returns the right temp
// for San Francisco, because I hardcoded the value into the url
return(
<div className="city-grid">
{this.state.cities.map(function(city,i){
return(
<CityRow key={i} name={city.name} temp={city.temp}
UTCOffset={city.UTCOffset} address={city.address}
phone={city.phone}/>
);
})}
</div>
);
}
});
module.exports = CityGrid;
我的问题:
- 如何提取温度值?在我的渲染函数中,console.log 返回 JSON 对象,这意味着数据已经绑定,可以在我的渲染函数中访问。但是,当我尝试获取温度时,我希望它类似于
this.state.data.main.temp,我收到“数据未定义”的错误。然后,我希望能够在我的城市对象中为这 12 个城市中的每一个设置这个值:id: 5391997,。
更新 ^^ 这已解决:@dkurbz 建议在我的 ajax 成功方法中将状态设置为 temp 对我来说很好。
- 我还面临如何为每个城市设置唯一的 url 的挑战。在我的 ajax 调用中,有
id=5391997,我想从城市对象中获取它并将我的 ajax url 更改为类似'baseURl' + this.props.id + '&units=imperial'。我完全不知道如何做到这一点。
更新 ^^这是我目前卡住的地方。
【问题讨论】:
-
你能发布那个console.log的结果吗?你在哪一行得到错误?
-
当然,在我的渲染函数中是console.log(this.state.data.main.temp),我的控制台显示“Uncaught TypeError: Cannot read property 'main' of undefined”
-
可能是因为您没有在初始状态中设置数据。在ajax回来之前,this.state.data是未定义的。
-
您是否尝试过我发布的代码?因为我只是在 jsfiddle 中运行它,而且效果很好。
标签: javascript jquery json ajax reactjs