如何根据状态更改索引路由

时间:2016-09-01 21:41:23

标签: redux react-router react-redux

假设我有以下主要的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,当IndexRoute为真时,我想将ShowEntries的组件更改为isLoggedIn并返回{{1}如果它变得虚假。我不知道如何实现这一点,但可以想到几个方面:

  1. 使用LoginRequiredPage上的react-redux connect方法将IndexRoute映射到其isLoggedIn属性的新值。
  2. 创建component组件,将其连接到商店,根据Home切换其子组件,并将isLoggedIn作为新的Home组件
  3. 哪个选项更好还是有更好的解决方案?

    当索引路由处于活动状态且IndexRoute状态发生变化时,我希望当前视图发生变化。

1 个答案:

答案 0 :(得分:1)

最直接的方法是声明一个组件,该组件将根据商店的某些属性的值返回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

相关问题