无法从反应路由器链接访问此.props.location



我正在使用 react-router v4,我正在尝试通过这样的链接传递一些道具

Page.js render
<Link to={{
pathname= "loosePath/" + this.id,
state = {
name = this.name
author = this.author
}
}}>
<div className="pageComponent"></div>
</Link>

但是,我无法访问到达页面上的this.props.location。 我认为这是因为我在Route组件中使用了render而不是component

Main.js render
<Switch>
...
<Route path="/loosePath" render={()=><Component2 someProps={props} />}></Route>
...
</Switch>

如果我将其更改为

<Route path="/loosePath" component={Component2}></Route>

我可以毫无问题地访问this.props.location.state。但是,通过这样做,我无法在"全局级别"通过Main.js中的某些道具。(Link旨在传递一些"局部"变量,如果这个类比有任何意义的话。

处理此类情况的最佳做法是什么?

render函数获取路由道具(matchlocationhistory(作为单个对象参数。

一种解决方法是仅使用这些:

<Route 
path="/loosePath" 
render={(routeProps) => <Component2 someProps={props} {...routeProps} />}
></Route>

在这里,我们解构作为道具传递给Component2routeProps。通过这种方式,您可以将自定义道具和路由道具传递给您的组件。


但是,推荐的方法是将Component2作为孩子传递:

<Route 
path="/loosePath" 
>
<Component2 someProps={props} />
</Route>

这样做不会像在rendercomponentchildren function方法中那样添加路由道具。相反,您将利用withRouter来访问类组件中的路由道具,或功能组件中的可用hooks

例如,如果Component2是一个功能组件,您将获得如下所示的位置:

const Component2 = (props) => {
let location = useLocation();
...

或者作为类组件,您只需使用withRouter包装导出的组件:

class Component2 extends Component {
render() {
this.props.location
...
export default withRouter(Component2)

最新更新