Javascript React js,打印出React组件';s状态不是空的,但调用this.state时,所有数据都消失了

Javascript React js,打印出React组件';s状态不是空的,但调用this.state时,所有数据都消失了,javascript,reactjs,Javascript,Reactjs,在React组件的componentDidMount()中,我发出axios get请求以接收响应并设置组件的状态。响应是正确的,当使用this打印组件类中的组件对象时,对象看起来很好。然后我调用console.log(this.state),然后组件的每个属性都变为空。为什么会发生这种情况?我怎样才能得到国家的财产 MyComponent.js React组件安装方法: componentDidMount() { getLastWeek(this); // here I ma

在React组件的componentDidMount()中,我发出axios get请求以接收响应并设置组件的状态。响应是正确的,当使用
this
打印组件类中的组件对象时,对象看起来很好。然后我调用
console.log(this.state)
,然后组件的每个属性都变为空。为什么会发生这种情况?我怎样才能得到国家的财产

MyComponent.js
React组件安装方法:

    componentDidMount() {

    getLastWeek(this); // here I make a get request

    console.log('===');
    console.log(this); // this line prints out an object will all the properties
    console.log(this.state); // all properties of state disappear
}
上面使用的get请求: service.js

...
    function getLastWeek(component) {

    const lastWeek = getEndpoint(7);

    Axios.get(lastWeek)
        .then(res => {

            const bpi = res.data.bpi;
            const prices = Object.values(bpi);

            component.setState({ lastWeek: prices });
        })
        .catch(err => {
            console.log(err);
        });
}
...

您正在发出一个axios请求,这是一个异步函数,因此您正在设置状态之前使用
console.log(this.state)

每次状态更改时都会执行
render()
方法,因此如果将
console.log
放在
render()
方法中,现在应该可以看到状态如何更改。大概是这样的:

class Example extends Component {
    constructor() {
        ...
    }
    componentDidMount() {
        ...
    }
    render() {
        console.log(this.state);
        return(...);
    }
}

我不会在componentdidmount设置状态中进行异步调用。有道理。。。但是为什么第一个
console.log
获得新状态,而后面的一个没有?它是在第一个控制台之前调用的第二个
控制台.log
?但在控制台中,它会在第一个log语句之后打印