React不能在axios外部分配类字段

时间:2018-01-29 07:16:43

标签: 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中分配但不在外部?

2 个答案:

答案 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>
        );
    }
}