【问题标题】:How to change index route depending on state如何根据状态更改索引路由
【发布时间】:2016-09-01 21:41:22
【问题描述】:

假设我有以下主要的 React 应用程序,使用 react-reduxreact-router(但还不是 react-router-redux):

<Provider store={store}>
  <Router history={hashHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={LoginRequiredPage}/>
      <Route path="/login" component={Login} />
      <Route path="/entries" component={ShowEntries} />
    </Route>
  </Router>
</Provider>

在我的商店中,我的状态为 isLoggedIn,当isLoggedIn 为真时,我想将IndexRoute 的组件更改为ShowEntries,如果它变为假,则改回LoginRequiredPage。我不确定如何实现这一点,但可以想到几种方法:

  1. 使用 IndexRoute 上的 react-redux connect 方法将 isLoggedIn 映射到其 component 属性的新值。
  2. 创建一个Home 组件,将其连接到商店,根据isLoggedIn 切换其子组件,并将Home 作为新的IndexRoute 组件

哪个选项更好,或者有更好的解决方案?

我希望在索引路由处于活动状态并且isLoggedIn 状态发生更改时更改当前视图。

【问题讨论】:

  • 我的答案是第二个选项。您不能简单地将RouteRouter 连接到Store,因此您需要通过Routecomponent 属性提供连接的组件,或者使用您创建的商店直接在路由器配置中执行一些重定向魔术早一点。

标签: redux react-router react-redux


【解决方案1】:

最直接的方法是声明一个组件,该组件将根据 Store 的某些属性的值返回 ShowEntriesLoginRequiredPage

<Provider store={store}>
  <Router history={hashHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Index}/>
      <Route path="/login" component={Login} />
      <Route path="/entries" component={ShowEntries} />
    </Route>
  </Router>
</Provider>

@connect(state => ({
  isLoggedIn: ... // <- place the correct value here
}))
class Index extends Component {
  render() {
    const {
      isLoggedIn
    } = this.props;

    if (isLoggedIn) {
      return <ShowEntries />
    } else {
      return <LoginRequiredPage />
    }
  }
}

另一种方法是检查用户是否已根据通过onEnter 属性输入的每条路线登录,并重定向到特定路线,但这意味着您显然会更改用户在浏览器中看到的位置。但如果您好奇,请查看this tip

【讨论】:

  • 如果你想在 onEnter 钩子的异步调用中获取数据怎么办。我的意思是每个组件的不同数据(例如使用 async-connect 或类似的东西)。你会怎么解决这个问题?
  • 那是一个单独的话题。但请记住,一旦组件被连接,它会根据它通过 connect 的 props 中的状态属性的每一次变化而更新(渲染)。将分为两个阶段:我们不知道用户是否登录(null),然后我们知道用户是否登录(true)或未登录(false)。设置新值并根据它们呈现这个和那个将是解决方案。
猜你喜欢
  • 2020-04-26
  • 2017-03-03
  • 2019-05-20
  • 1970-01-01
  • 2015-06-23
  • 2016-02-26
  • 2020-12-08
  • 2020-03-20
  • 2019-07-17
相关资源
最近更新 更多