2017-11-14 4 views
3

React、ReduxとReact-routerを使用して、私はredux状態に応じて同じルートに異なるコンポーネントをバインドしたいと思います。例えば:ComponentAとComponentBを想定すると、還元反応状態に応じて同じ反応ルータ経路で異なる反応成分をバインドする方法はありますか?

は、私は、これはルータの設定に/routes.js

<Route path="/" component={App}> 
    <Route path="/test" component={ComponentA} /> 
</Route> 

が、私の場合に反応が欲しい私はこのReduxの状態

{ 
    flag: true; 
} 

を持っていると仮定するとコンポーネント

に反応しています私のRedux状態にあるflagfalseにしたい

... 
    <Route path="/test" component={ComponentB} /> 
... 

私はComponentAにラッパーコンポーネントを作成することができることを知っていますし、Reduxの状態をチェックして、対応するコンポーネントをレンダリングComponentBが、私は新しいコンポーネント

を作成する必要がない答えを探していました

答えて

1

routeのコンポーネントフィールドには、terinary演算子を使用できます。

<Route path="/test" component={flag ? ComponentA : ComponentB} /> 

編集:これは、状態から旗にマップする方法です。

import { connect } from 'react-redux'; 

// ... Component Definition 

const mapStateToProps = (state, ownProps) => { 
    return { 
    flag: state.flag 
    } 
} 

const mapDispatchToProps = (dispatch, ownProps) => { 
    return { 
    // Whatever you want to dispatch 
    } 
} 

const ConnectedComponent = connect(
    mapStateToProps, 
    mapDispatchToProps 
)(YourComponent) 

編集2:Provider

const Root = ({ store }) => (
    <Provider store={store}> 
    <Router> 
     <Route path="/" component={App} /> 
    </Router> 
    </Provider> 
) 
+0

を使用してReduxのにルータを反応させるの接続はどのようにしてReduxの状態からフラグを得るのですか? –

+0

それはあなたのプロジェクトの残りの仕方によって異なりますが、一般的に 'react-redux'から' connect' HOCを使い、引数として取るmapStateToProps関数のフラグpropをマップします。 – Dakota

+0

私はこれをどのように行うことができるかを示すために私の答えを編集しました。 – Dakota

関連する問題