javascript - 无法将全局变量设置为等于 Promise 返回的值

标签 javascript asynchronous react-native promise axios

我正在尝试在我的 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。

最佳答案

  1. 如果您希望组件的 View 根据新数据进行更新,则需要使用 setState 来告诉 React 重新渲染。 React 不会对常规类属性使用react(色调)。

  2. 不应从渲染中调用异步函数。您应该使用 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/

相关文章:

javascript - 使用 twig 日期时间中的日期实现 googlechart x 轴

javascript - Firebase:如何停止收听快照

c# - 在页面中异步加载用户控件

javascript - 有没有办法共享特定的应用程序 ios?

javascript - 为什么 ng-click 不会在组件模板中触发?

javascript - 如何使用作为函数参数传递的对象?

python - 将 python 函数列表异步应用于单个参数

Java 异步正在阻塞?

react-native - 防止关闭键盘。 react native

ios - 在 Debug模式下,API 请求有效。 Release模式,返回 null