【问题标题】:My props are valued undefined under ComponentDidMount method in React我的道具在 React 的 ComponentDidMount 方法下的价值未定义
【发布时间】:2020-12-15 11:24:57
【问题描述】:

为什么我在this.propsthis.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 {
    
    }
}

【问题讨论】:

    标签: javascript reactjs components react-props react-state


    【解决方案1】:

    this.setState 是异步的,这意味着之后的函数不会等到它完成,所以如果你 console.log 更新后你的状态可能仍然具有旧值。

    要解决此问题,您可以在 render 中检查您的状态值,它最终会更新,或者您可以运行 setState 并带有这样的回调

    this.setState({iscreator: true}, () => console.log(this.state.iscreator) )
    

    这确保仅在 setState 完成后运行 console.log

    【讨论】:

    • 是的,但为什么我的 this.props.token 和 this.state.training.coach 值未定义?
    • 因为它只需要一小部分时间就可以更新,而当您单击调用handleDelete 的按钮时,setState 已经完成。
    • 但是当我将这些值控制在 setState 之上时,它们应该有一些东西。为什么那些是空的?或者我应该怎么做才能让它工作?
    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 2021-05-17
    • 2021-01-26
    • 2018-09-20
    • 2016-11-08
    • 2018-04-18
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多