2016-11-07 10 views
0

反応ルータのパラメータオブジェクトをコンポーネントに明示的に渡す方法を知っている人はいますか?明示的にルータのパラメータをReact Componentに渡す方法は?

私は外から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} 
    /> 
}/> 

あなたは今MyCoolComponent

this.props.paramsthis.props.myCustomApiKeyアクセスすることができます
関連する問題