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
放入回调中。