无法在React类Component中的函数中访问道具和状态

问题描述

我正在尝试从状态和道具中获取值。该函数在componentwillReceiveProps方法下触发。但是,当我尝试通过该功能控制台记录我的道具和状态值时,结果为“未定义”。与我的状态更新速度不够快有关吗?我是否想在某个地方传递道具?哪里有错误,我该如何处理正确的值?

handleShow()函数

state = {
    training: {},isCreator: null
}

componentwillReceiveProps(newProps) {
console.log(newProps);
    if (newProps.token) {
        axios.defaults.headers = {
            "Content-Type": "application/json",Authorization: newProps.token
        }
        const trainingID = this.props.match.params.trainingID;
        axios.get(`http://127.0.0.1:8000/api/${trainingID}/`)
            .then(res => {
                this.setState({
                    training: res.data
                });
                console.log('treener',res.data.coach)
            })
            .catch(err => {console.log(err)})
        this.handleShow()
    } else{}

}

handleShow() {
    if(this.props.token == this.state.training.coach) {
        console.log('Props:',this.props.token);// value of undefined
        console.log('State.training',this.state.training.coach)// 
        this.setState({
            isCreator: true
        })
    }else{
        this.setState({
            isCreator: null
        })
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)