【问题标题】:Cannot set a global variable equal to a value returned from a Promise无法将全局变量设置为等于从 Promise 返回的值
【发布时间】: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


【解决方案1】:
  1. 如果你想让你的组件视图更新以响应新数据,你需要使用 setState 来告诉 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>
    )
  }
}

【讨论】:

  • 使用状态似乎可以解决这个问题。谢谢! React Native 对我来说是全新的——他们似乎没有在 Uni 教授这些东西。干杯!
【解决方案2】:

如果你想分配给一个独立变量(即使它恰好在全局范围内),不要在它前面加上this。只是

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

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

【讨论】:

    【解决方案3】:

    这个答案是错误的,箭头允许https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)注意关键字“this”。 当前正在将 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>
      );
     }
    }
    

    【讨论】:

    • 一个好主意,但箭头函数是绕过这个 c:
    • 完全正确!将保留它用于教育目的,谢谢你赶上我
    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多