我正在尝试在我的 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。
最佳答案
如果您希望组件的 View 根据新数据进行更新,则需要使用 setState 来告诉 React 重新渲染。 React 不会对常规类属性使用react(色调)。
不应从渲染中调用异步函数。您应该使用 lifecycle hooks ,而
componentDidMount
最适合这种情况,在安装时获取信息。
考虑到这一点,你最终会得到这样的结果:
class Example extends React.Component {
state = {
data: null
}
componentDidMount() {
// fetch forecast data when the component mounts
this._getForecast(49306)
}
_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.setState({ data: response.data })
}
})
}
render() {
if (this.state.data === null) {
// don't render if we haven't received data yet
// otherwise we'll get an error trying to calculate temp_high
return
}
const temp_high = Number(
this.state.data.forecast.simpleforecast.forecastday[0].high.fahrenheit
)
return (
<View style={styles.container}>
<Text>Weather for Belmont, MI</Text>
<Text>High: {temp_high}</Text>
<Text />
</View>
)
}
}
关于javascript - 无法将全局变量设置为等于 Promise 返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49375509/