2016-11-07 68 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

相關問題