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

时间:2018-03-20 02:35:59

标签: 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。

3 个答案:

答案 0 :(得分:3)

  1. 如果您希望更新组件的视图以响应新数据,则需要使用setState来告诉React重新渲染。 React不会对常规类属性做出反应(色调)。

  2. 不应从渲染中调用异步函数。您应该使用lifecycle hooks,而componentDidMount最适合这种情况,在mount上获取一次信息。

  3. 考虑到这一点,你最终会得到这样的东西:

    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>
        )
      }
    }
    

答案 1 :(得分:1)

如果要分配独立变量(即使它恰好位于全局范围内),请不要在其前面添加this。刚

temp_high = Number(data.forecast.simpleforecast.forecastday[0].high.fahrenheit);

this解析为您所在当前函数的调用上下文。

答案 2 :(得分:-1)

这个回答是错误的,箭头允许https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions )小心使用关键字&#34; this&#34;。 它目前正在将this.temp_high设置为_getForecast函数。您可能想要做的是

 render() {
var self = this;
 this._getForecast(49306).then(data => {
 self.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>
  );
 }
}
相关问题