2016-11-07 65 views
0

有没有人有一个想法如何显式传递react-router params对象给组件?如何显式传递路由器参数给React组件?

我想让这样的事情,因为单元测试会更容易,如果我可以从外面通过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> 

回答

1

如果您的组件连接到路由(即设置为component道具Route与您提供的代码一样),它会从react-router接收支持params,您可以在其中获取路由和查询参数。你的情况:

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

0

你也可以考虑像这样通过关闭路由器的道具和添加一些自定义道具,你的组件,例如。 我不知道它是什么地方记录在反应路由器文档

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

您现在可以访问this.props.paramsthis.props.myCustomApiKey在MyCoolComponent

相关问题