首页 文章

如何根据redux状态使用相同的反应路由器路由绑定不同的反应组件?

提问于
浏览
3

使用React,Redux和React-router,我想根据redux状态将不同的组件绑定到同一路由 . 例如:

假设ComponentA和ComponentB是React组件

假设我有这个redux状态

{
  flag: true;
}

我想要这个React Router配置 /routes.js

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

但如果我在我的Redux状态下 flagfalse 我想拥有

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

我知道我可以创建一个包装器组件 ComponentAComponentB 来检查redux状态,然后渲染相应的组件,但我正在寻找一个不需要创建新组件的答案

1 回答

  • 1

    您可以在路径的组件字段中使用三元运算符 .

    <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 将React路由器连接到Redux

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

相关问题