【发布时间】:2017-01-19 01:08:55
【问题描述】:
我编写了一个小的反应组件,它从开放的天气 api 中获取一些数据。获取成功,我可以在响应中获取一个 json 对象。
然后我使用 this.setState({}) 将此响应保存到组件状态
并且反应开发工具显示预测对象实际上保存在状态中。
但是,当我开始渲染任何数据时,我总是会收到一条错误消息,指出“无法读取 null 的属性“预测”。
下面是反应组件和对象本身的屏幕截图。
export default class Weather extends Component {
getWeather () {
var self = this;
fetch('http://api.openweathermap.org/data/2.5/weather?zip=sl44jn,uk&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c')
.then (function (response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' + response.status);
return;
}
response.json().then(function(data) {
self.setWeather(data);
});
})
.catch (function (err) {
console.log('Fetch Error :-S', err);
});
}
setWeather (forecast) {
console.log(forecast);
this.setState({
forecast: forecast.name
})
}
componentWillMount () {
this.getWeather();
}
componentDidMount () {
// window.setInterval(function () {
// this.getWeather();
// }.bind(this), 1000);
}
render() {
return (
<h1>{this.state.forecast}</h1>
)
}
}
这是数据对象本身,现在我只是尝试访问 name 属性。
【问题讨论】: