如何解决无法与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)
问题:
- 这是完成我要实现的功能的最佳方法吗?
- 如何使用
history
对象正确设置组件中的状态?
背景:我使用Router
而不是BrowserRouter
,以便可以使用通过历史记录包创建的自己的历史记录对象。我正在使用withRouter
连接我的MealSummary
组件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。