【问题标题】:How to access child route params in react router如何在反应路由器中访问子路由参数
【发布时间】:2020-01-01 11:36:03
【问题描述】:

我正在尝试从父组件访问路由参数。我知道使用 withRouter 你只能访问最近的父路由参数。因此,在父组件中访问当前路由参数的解决方案是什么?我正在使用反应路由器 v5。

【问题讨论】:

  • 你能给我们提供一些你想如何使用它的上下文吗?

标签: reactjs react-router


【解决方案1】:

如果我的问题正确,您可以在 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}/>
    )
}

【讨论】:

  • 是的,就是这个意思。看起来还可以。但我认为可能有更好的解决方案。谢谢。
猜你喜欢
  • 2021-05-20
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
相关资源
最近更新 更多