问题描述
为什么在我的this.props
方法中未定义this.state
和componentDidMount
下的值?在类组件的其他部分,我可以正确访问道具和状态值。我是否需要将它们分别传递到某个地方或我犯了任何错误的地方?
我没有任何值:
componentDidMount() {
console.log(this.props.token)
console.log(this.state.training.coach)
// values are null and undefined.
if (this.props.token == this.state.training.coach) {
this.setState({
iscreator: true
});
console.log(this.state.iscreator)
} else {
this.setState({
iscreator: false
});
}
}
访问this.props.token
时得到正确的值:
handleDelete = (event) => {
if (this.props.token !== null) {
const trainingID = this.props.match.params.trainingID;
axios.defaults.headers = {
"Content-Type": "application/json",Authorization: this.props.token
}
axios.delete(`http://127.0.0.1:8000/api/${trainingID}/`)
this.props.history.push('/');
this.forceUpdate();
} else {
}
}
解决方法
this.setState
是异步的,这意味着之后的功能不会等到完成后再运行,因此如果您在更新后立即console.log
修改状态,则它可能仍具有旧值。
要解决此问题,您可以在render
中检查状态值,状态值将最终更新,或者您可以运行带有此类回调的setState
this.setState({iscreator: true},() => console.log(this.state.iscreator) )
这确保仅在完成console.log
之后才运行setState
。