【发布时间】:2018-08-28 18:05:04
【问题描述】:
我试图在我的 React Native 应用程序中设置一个全局变量,该变量等于从 Axios 的 Promise 返回的 JSON 元素。我遵循了this question 的建议,但仍然无法设置变量的值。
这是我使用 Axios 调用的方法:
temp_high = null;
_getForecast(zipcode)
{
const request = "http://api.wunderground.com/api/" + API_KEY + "/forecast/q/" + zipcode + ".json";
return axios.get(request).then( (response) => {
if(response.status == 200) {
this.response = response.data;
return this.response;
}
});
}
还有我的渲染:
render() {
this._getForecast(49306).then(data => {
this.temp_high = parseInt(data.forecast.simpleforecast.forecastday[0].high.fahrenheit);
});
return (
<View style={styles.container}>
<Text>Weather for Belmont, MI</Text>
<Text>High: {this.temp_high}</Text>
<Text></Text>
</View>
);
}
}
如果我将data.forecast.simpleforecast.forecastday[0].high.fahrenheit 记录到控制台,或者创建一个调用它的警报,则该值确实是正确的。我似乎无法将其设置为等于 temp_high。
【问题讨论】:
-
您的异步操作不会在渲染之前完成。不能这样。我不知道自己的反应,但它可能有不同的方式将异步操作合并到渲染操作中。
-
什么是合适的解决方案?我可以在某处添加一个等待点以确保它完成吗?
标签: javascript asynchronous react-native promise axios