如何解决我的道具在React中的ComponentDidMount方法下价值未定义
为什么在我的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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。