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中分配但不在外部?
答案 0 :(得分:1)
这并不难理解,axios.get
是异步函数,因此console.log
之前会调用axios.get
。
考虑:
|
|\_____________
console.log |
| axios.get
| |
\ ??? /
您无法知道将首先调用哪一个。通常不是axios.get
。
如果要打印数据,请将console.log
置于回调中。
答案 1 :(得分:0)
通过使用Axios,它将创建一个Promise。 .then
发生在(当承诺解决时){axer console.log
之外的.then
之后。
另外,对于它的价值,设置像你这样的值是反模式。
以下是我将如何更改您的代码:
class App extends React.Component {
state = {
currentUser: "" // <-- making an assumption that the response is just a string.
}
componentDidMount() { // <-- note the actual spelling
axios.get("http://example.com/").then(res => {
this.setState({
currentUser: res.data.data
});
});
}
render() {
const { currentUser } = this.state;
// On initial render currentUser will be an empty string. Once the axios call resolves the setState will be called
// and it will re-render with the new data.
return (
<div>{currentUser}</div>
);
}
}