【发布时间】:2020-01-01 11:36:03
【问题描述】:
我正在尝试从父组件访问路由参数。我知道使用 withRouter 你只能访问最近的父路由参数。因此,在父组件中访问当前路由参数的解决方案是什么?我正在使用反应路由器 v5。
【问题讨论】:
-
你能给我们提供一些你想如何使用它的上下文吗?
标签: reactjs react-router
我正在尝试从父组件访问路由参数。我知道使用 withRouter 你只能访问最近的父路由参数。因此,在父组件中访问当前路由参数的解决方案是什么?我正在使用反应路由器 v5。
【问题讨论】:
标签: reactjs react-router
如果我的问题正确,您可以在 childs componentDidUpdate 中捕获当前匹配道具并将其作为道具传递。像这样:
child.js:
//skipping the class definition and render method
componentDidUpdate(prevProps){
// when location gets updated in child component
if(JSON.stringify(this.props.match)!=JSON.stringify(prevProps.match)){
//match.id or whatever param you need in parent component
this.props.cb(this.props.match.id);
}
}
父母:
handleParamUpdate(id){
console.log(id)
}
render(){
return(
<Child cb={this.handleParamUpdate}/>
)
}
【讨论】: