【问题标题】:componentDidUpdate - What am i doing wrong?componentDidUpdate - 我做错了什么?
【发布时间】:2021-04-19 12:05:34
【问题描述】:

我正在尝试使用 MERN 堆栈将错误消息从后端带到前端。我能够在开发人员工具中接收错误消息,但无法在 UI 中显示消息。我正在使用 Redux 作为状态管理器。当我提交表单时,concomponentDidUpdate 中的 console.log() 不起作用。有人可以澄清我的代码有什么问题吗?

state = {
        name: '',
        email: '',
        phoneNo: null,
        dateOfBirth: new Date,
        gender: 'Select',
        education: '',
        checkBox: false,
        msg: null
    }

    static propTypes = {
        addInfo: PropTypes.func.isRequired,
        info: PropTypes.object.isRequired,
        error: PropTypes.object.isRequired
    }

    componentDidUpdate(prevProps, nextProps) {
        const { error } = this.props;

        if (error !== nextProps.error) {
            console.log("Working");
            if (error.id === 'REGISTER_FAIL')
                this.setState({ msg: error.msg.msg });
            else
                this.setState({ msg: null });
        }
    }

【问题讨论】:

    标签: node.js reactjs mongodb express redux


    【解决方案1】:

    componentDidUpdate() 不会在初始挂载时调用,只会在组件重新渲染期间调用。

    如果您需要在初始挂载以及后续更新中调用它,请将其复制到 componentDidMount 或使用静态 getDerivedStateFromProps

    【讨论】:

    • 首先,我正在提交一个表单,当它捕获到错误时,它会进入 redux 的错误状态。因此,它不是初始安装。你能想到别的吗?
    【解决方案2】:

    按照此文档,componentDidUpdate 接收 3 个参数:prevProps、prevState 和 snapshot。

    在您的代码中,您像下一个 props 一样使用它:

    componentDidUpdate(prevProps, nextProps)
    

    应该是这样的:

    componentDidUpdate(prevProps, prevState){
        const { error } = this.props;
    
            // React will call didUpdate after component is updated
            // this.props is the nextProps.error as you trying to do
            if (error !== prevProps.error) {
                console.log("Working");
                if (error.id === 'REGISTER_FAIL')
                    this.setState({ msg: error.msg.msg });
                else
                    this.setState({ msg: null });
            }
    }
    

    或者你会想要使用UNSAFE_componentWillReceiveProps

    UNSAFE_componentWillReceiveProps(nextProps){}

    【讨论】:

    • 这也不起作用。你能想到别的吗?
    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 2021-04-14
    • 2017-03-13
    • 2017-01-18
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多