有没有人知道如何将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>
答案 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.params
和this.props.myCustomApiKey