React 无法在 axios 之外分配 class 字段
React cannot assign class field outside 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
之前被调用。
考虑:
|
|\_____________
console.log |
| axios.get
| |
\ ??? /
您无法知道哪个将首先被调用。通常 axios.get
不在这里。
如果要打印数据,将console.log
放入回调。
通过使用 Axios,它将创建一个 Promise。 .then
发生在 axios .then
.
之外的 console.log
之后(当承诺解决时)
此外,就其价值而言,像您这样设置值是一种反模式。
以下是我将如何更改您的代码:
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>
);
}
}
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
之前被调用。
考虑:
|
|\_____________
console.log |
| axios.get
| |
\ ??? /
您无法知道哪个将首先被调用。通常 axios.get
不在这里。
如果要打印数据,将console.log
放入回调。
通过使用 Axios,它将创建一个 Promise。 .then
发生在 axios .then
.
console.log
之后(当承诺解决时)
此外,就其价值而言,像您这样设置值是一种反模式。
以下是我将如何更改您的代码:
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>
);
}
}