简体   繁体   English

API请求后,ReactJS状态正在更新

[英]ReactJS state is being updated after an API request

I'm having an issue with React state. 我在React状态上遇到问题。 It receives an array of objects and it's being set properly in state, but then function finishes it shows that state is empty. 它接收到一个对象数组,并且已正确设置了状态,但是函数完成后显示状态为空。 Can anyone explain this behaviour? 谁能解释这种行为?

  componentDidMount() {
    this.getWeather();
    this.getForecast();
    this.setState({location: ''});
  }

  getWeather() {
    if (this.state.location === "") {
      this.setState({error: 'Please enter something'});
    } else {
      OpenWeather.getWeather(this.state.location).then(result => {
        if (result.cod === "404") {
          this.setState({error: 'City not found'});
        } else if (result.cod === 200) {
          this.setState({error: ''});
          this.setState({weather: result});
        } else {
          this.setState({error: 'Server error'});
        }
      });
    }
  }

  getForecast() {
    OpenWeather.getForecast(this.state.location).then(forecast => {
      console.log("Returned forecast:");
      console.log(forecast);
      this.setState({forecast: forecast});
      console.log("Forecast saved to state(inside function)");
      console.log(this.state.forecast);
    });
    console.log("Forecast saved to state(outside function)");
    console.log(this.state.forecast);
  }

Console output: 控制台输出:

Forecast saved to state(outside function)
[]
Returned forecast:
(5) [{…}, {…}, {…}, {…}, {…}]
Forecast saved to state(inside function)
(5) [{…}, {…}, {…}, {…}, {…}]

There are two things, conceptually wrong. 有两件事,从概念上讲是错误的。

First: Your API requests to OpenWeather. getForecast 首先:您的API请求OpenWeather. getForecast OpenWeather. getForecast is asynchronous and hence before your API returns a response the Javascript code after it is being executed and hence you get the first response as OpenWeather. getForecast是异步的,因此,在您的API返回响应之前,执行后的Javascript代码因此得到第一个响应为

Forecast saved to state(outside function)
[]

Now when the Api results in Success, you get 现在,当Api取得成功时,您将获得

Returned forecast:
(5) [{…}, {…}, {…}, {…}, {…}]

Second: Since setState is asynchronous, your third statement 第二:由于setState是异步的,因此您的第三条语句

console.log("Forecast saved to state(inside function)");
console.log(this.state.forecast);

may or may not give you the updated value. 可能会或可能不会为您提供更新的值。 You should instead make use of setState callback. 您应该改为使用setState回调。

Check these question for more info 检查这些问题以获取更多信息

When to use React setState callback 何时使用React setState回调

calling setState doesn't mutate state immediately 调用setState不会立即改变状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM