异步调用后状态变为未定义

时间:2019-03-23 18:08:59

标签: reactjs express

试图了解为什么组件状态变得不确定。  在异步调用之前,控制台将this.state.pubsubtopics显示为[],在调用之后,控制台变为未定义

代码:

class PubSubTopics extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            pubsubtopics: [],
        };
    }

    componentDidMount() {
        console.log('after component mounted');
        console.log(this.state.pubsubtopics);
        this.callBackEndAPI()
            .then(res =>
                this.setState({pubsubtopics: res.express}))
            .catch(err => console.log(err));
        console.log('after setting state');
        console.log(this.state.pubsubtopics);
    }

    callBackEndAPI = async () => {
        const response = await fetch('/listtopics');
        const body = await response.json();

        if(response.status !== 200){
            throw Error(body.message)
        }
        return body;
    }

    handlePrintStateClick = () => {
        console.log(this.state.pubsubtopics);
    }

    render(){
        return(
            <div>
                <ul>
                </ul>
                <button onClick={this.handlePrintStateClick}>printState</button>
            </div>
        )
    }
}

日志(最后一个日志条目来自单击按钮):

after component mounted
index.js:16 []
index.js:21 after setting state
index.js:22 []
index.js:36 undefined

1 个答案:

答案 0 :(得分:0)

res.express在服务器的响应中不存在,使用res.topics解决了问题