如何明确地将路由器参数传递给React组件?

时间:2016-11-07 23:09:33

标签: reactjs react-router

有没有人知道如何将react-router params对象明确地传递给组件?

我想制作这样的东西,因为如果我可以从外面传递ApiClient,单元测试会更容易:

function FooComponent() {
  const apiClient = new ApiClient('http://foo.bar');
  return (
    <Bar apiClient={apiClient} param={?No idea how to pass the token param?} />
  );
}

<Router history={history}>    
  <Route path="/test" component={Test} />
    <IndexRoute component={TestIndex} />
    <Route path="/validate/:token" component={FooComponent} />
</Router>

2 个答案:

答案 0 :(得分:1)

如果您的组件已附加到路线(即设置为component Route道具,与您提供的代码相同),则会从params收到道具react-router在哪里可以获取路由和查询参数。在你的情况下:

function FooComponent(props) {
  const apiClient = new ApiClient('http://foo.bar');
  return (
    <Bar apiClient={apiClient} param={props.params} />
  );
}

有关官方示例,请查看:https://github.com/ReactTraining/react-router/blob/master/examples/query-params/app.js

答案 1 :(得分:0)

你也可以考虑这样的东西传递路由器道具并为你的组件添加一些自定义道具。 我不知道它是否在react-router文档的某处记录了

<Route path="/campaign/overview" component={(routeProps) =>
    <MyCoolComponent
        myCustomApiKey="secret"
        {...routeProps}
    />
}/>

您现在可以在MyCoolComponent

中访问this.props.paramsthis.props.myCustomApiKey