【问题标题】:Can't see my state updated if i console.log outside the axios .then function如果我在 axios .then 函数之外使用 console.log,则看不到我的状态更新
【发布时间】:2019-11-16 16:11:03
【问题描述】:

我正在尝试在 React 中使用 Api 和 Axios 调用。我有这个问题。在 componentDidMount 我有这个 axios 调用:

componentDidMount() {
  axios.get("https://api.imgflip.com/get_memes").then(res => {
    const allMemeImgs = res.data.data.memes;

    this.setState({ allMemeImgs });

    console.log(this.state.allMemeImgs[0]);
  });
}

在初始状态下,我声明了一个空数组:

this.state ={
  allMemeImgs: []
}

现在,如果我在 Axios 获取请求中进行控制台登录,我可以看到我的状态已更新。但是,如果我尝试在外面登录,他们会给我一个错误或一个空数组。所以这可能意味着状态并没有真正用 api 数据更新。我在那里缺少什么? 谢谢

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    setState 是异步的,如果你想看到你必须做的更改。

    componentDidMount() {
      axios.get("https://api.imgflip.com/get_memes").then(res => {
        const allMemeImgs = res.data.data.memes;
    
        this.setState({ allMemeImgs }, () => {
          console.log(this.state.allMemeImgs[0]);
        });
      });
    }
    

    您应该使用setState 回调来保证您的状态发生变化。

    了解更多关于setStatehere

    【讨论】:

      【解决方案2】:

      当您调用axios.get 时,它会返回一个Promise

      Promise 不会立即得到解决。那是then块的代码被执行的时候(在promise被解决之后)。

      现在,axios 之后的 console.log 在调用 axios.get 时立即执行,不是在您收到响应时

      在这里,您可以在 then 块内设置您的状态 - 比如:

      axios
          .get(url)
          .then(response => {
              // here you get the response - it may take time for this code to be executed
              // set your state here
              console.log(response);
          }
      // this will be executed as your code will not know to wait for the response
      console.log(state.response); // you'll not get the response here as this is 
                                   // executed before the promise has resolved.
      

      还有一个更简洁的版本 - async/await。如果您可以花一些时间了解回调、promise 和 async/await 是如何工作的,那么所有的努力都是值得的。

      【讨论】:

        猜你喜欢
        • 2019-04-28
        • 1970-01-01
        • 2019-07-09
        • 1970-01-01
        • 2017-11-09
        • 2021-07-24
        • 1970-01-01
        • 2021-09-08
        • 2019-09-04
        相关资源
        最近更新 更多