无法与React路由器一起使用history.push来传递道具以声明要在父组件中使用

问题描述

我有一个父级组件MealSummary。我想使用生命周期方法componentDidMount来设置一个日期对象,或者使用一个代表今天日期的moment对象,或者将一个日期向下传递给使用history.push的子组件设置我要访问的状态的方法

MealSummary的一部分看起来像这样:

export class MealSummary extends Component {
    state = {
        calendarFocused: false
    }

    componentDidMount() {
        let date
        if (this.props.location.state) {
            date = this.props.location.state.date
            console.log('i am date: ',date);
        }

        this.setState({ date: date || moment() });
    }
.
.
...
}

我将日期对象通过几个孩子传递到EditMealPage。我希望将日期对象传递回父组件的原因是,如果我要编辑的一顿饭不是今天的日期,并且我对其进行了编辑,我希望用户返回到该日期的同一天。用户选择编辑餐点。当前的行为是,在编辑之后,无论当前的用餐日期如何,用户都可以通过编程方式返回到具有今天日期的主页。

我试图纠正该行为的方法是在此方法中使用history.push组件来使用EditMealPage

    onSubmit = e => {
        e.preventDefault()
        const { foodId,measureURI,quantity,uuid,mealCategory } = this.state
        const editsObj = {
            foodId,quantity: parseInt(quantity)
        }
        this.props.editServing(uuid,editsObj,mealCategory)
        this.props.history.push(
            {
                pathname: '/',state: { date: this.props.history.location.date }
            })
    }

但是,出现以下错误

history.js:357 Uncaught DOMException: Failed to execute 'pushState' on 'History': function (number) {
            var b = number % 10,output =
                    toInt((number...<omitted>... } Could not be cloned.
at http://localhost:3000/dist/bundle.js:8007:23
    at Object.confirmTransitionTo (http://localhost:3000/dist/bundle.js:7795:7)
    at Object.push (http://localhost:3000/dist/bundle.js:8000:23)
    at http://localhost:3000/dist/bundle.js:92617:27
    at HTMLUnkNownElement.callCallback (http://localhost:3000/dist/bundle.js:46811:14)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/dist/bundle.js:46860:16)
    at invokeGuardedCallback (http://localhost:3000/dist/bundle.js:46915:31)
    at invokeGuardedCallbackAndCatchFirstError (http://localhost:3000/dist/bundle.js:46929:25)
    at executedispatch (http://localhost:3000/dist/bundle.js:47012:3)
    at executedispatchesInorder (http://localhost:3000/dist/bundle.js:47037:5)

问题:

  1. 这是完成我要实现的功能的最佳方法吗?
  2. 如何使用history对象正确设置组件中的状态?

背景:我使用Router而不是browserRouter,以便可以使用通过历史记录包创建的自己的历史记录对象。我正在使用withRouter连接我的MealSummary组件。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...