【问题标题】:How to Bind different react components with the same react-router route depending on redux state?如何根据redux状态将不同的react组件绑定到相同的react-router路由?
【发布时间】:2018-04-27 12:11:01
【问题描述】:

使用 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 状态,然后渲染相应的组件,但我正在寻找不需要创建新组件的答案

【问题讨论】:

    标签: javascript reactjs redux react-router frontend


    【解决方案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 Router 连接到 Redux

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

    【讨论】:

    • 如何从redux状态获取flag?
    • 这取决于您项目的其余部分的外观,但通常您会使用来自react-reduxconnect HOC 并将 flag 属性映射到它作为参数的 mapStateToProps 函数中。
    • 我在上面编辑了我的答案,以展示如何做到这一点。
    • &lt;Route&gt; .. 在另一个文件中,所以基本上如果我这样做 flag? .. 标志是未定义的
    • 如果你想使用 redux 状态来确定你的路由,你必须将它连接到某个地方。我不知道你项目的架构,所以我不能告诉你在哪里做这个。只要您将Router 包装在Provider 组件中,您就应该可以访问redux 存储。你应该有一些看起来像我在第二次编辑中放置的东西,它允许你访问你的路由处理程序中的状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2023-03-17
    • 2019-01-07
    • 2020-09-12
    • 2021-08-04
    • 2018-08-06
    相关资源
    最近更新 更多