javascript - React 无法在 axios 之外分配类字段

标签 javascript reactjs typescript axios

class App extends React.Component {
  app: Application;

  ...
  componentDidMound() {
    axios.get(…).then(res => {
        this.app.currentUser = res.data.data; // value assigned here.
        console.log(this.app.currentUser); // and print the current user object.
    };
    console.log(this.app.currentUser); // but here print currentUser = undefined.
  }
}

为什么 this.app.currentUser 在 lambda 中分配而不是在外部?

最佳答案

不难理解,axios.get是一个异步函数,所以console.log会在axios.get之前调用.

考虑:
| |\_____________ 控制台日志 | | axios.get | | \???/ 您无法知道将首先调用哪一个。通常这里不是 axios.get 。 如果要打印数据,请将 console.log 放入回调中。

关于javascript - React 无法在 axios 之外分配类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48496183/

相关文章:

javascript - Jquery attr 不向按钮添加工作 ID

javascript - Apollo 服务器 - GraphQL 错误 : There can be only one type named "Query"

javascript - 在 JavaScript 中重定向

reactjs - React hooks 引用值对比

javascript - 未捕获的类型错误 : Cannot read property 'value' of null (React js component id passing other component)

javascript - 在 Google Adwords 脚本中加载外部 JS 文件

javascript - 为什么在计算函数时输入属性被调用数百次

typescript - 如何在不使用 FileTransfer 的情况下从 Ionic 5 中的 url 下载文件

javascript - 在 typescript+Angular 项目中使用 requirejs (-m amd) 的优点和缺点

ios - React Native 显示神秘的堆栈跟踪而不是文件名