如何在React Router中访问子路由参数

时间:2019-08-28 09:22:04

标签: reactjs react-router

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

1 个答案:

答案 0 :(得分: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}/>
    )
}
相关问题