在React中的ComponentDidMount方法下,我的道具的值未定义



为什么我的componentDidMount方法中未定义this.propsthis.state下的值?在类组件的其他部分,我可以正确地访问我的道具和状态值。我需要把它们分别传给某个地方吗?或者我在哪里犯了错误?

我没有得到任何值:

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) )

这确保只有在setState完成之后才运行console.log

相关内容

最新更新