【问题标题】:Dynamic React-Router routes动态 React-Router 路由
【发布时间】:2016-09-27 20:01:35
【问题描述】:

我想根据部分状态使用不同的路由,所以我想出了以下内容:

在我的条目文件中:

import routes from './routes.js'

ReactDOM.render(
  <IntlProvider locale={locale} messages={messages[locale]}>
    <Provider store={store} key='provider'>
      <div>
        <Router history={history} routes={routes(store)} />
      </div>
    </Provider>
  </IntlProvider>,
  document.getElementById('root')
)

routes.js:

export default (store) => (
  let isAuthenticated = store.getState().auth.isAuthenticated

  if(isAuthenticated) {
    return (
      <Route component={Tool}>
        <IndexRoute component={Dashboard} />
        <Route path="products" component={Products} />
      </Route>
    )
  } else {
    return (
      <Route>
        <Route component={Site}>
          <IndexRoute component={Home} />
          <Route path="pricing" component={Pricing} />
        </Route>
        <Route component={Portal}>
          <Route path="login" component={Login} />
          <Route path="register" component={Register} />
        </Route>
      </Route>
    )
  }
)

这有效,但前提是我真的刷新了页面。如果我只是登录而不刷新浏览器页面,它将但是不会转换从 Home 组件到 Dashboard 组件,所以我怀疑 routes 对象在开始时只构建一次并建立在当前状态上,但是如果状态在执行过程中改变,则不会改变。

我还发现 https://github.com/ReactTraining/react-router/blob/master/docs/guides/DynamicRouting.md 这与动态路由有关,但当我尝试它时,它似乎并没有达到我希望或预期的效果。

【问题讨论】:

标签: reactjs redux react-router react-router-redux


【解决方案1】:

您可以在路由级别使用onEnter 方法

<Route name="example" path="/example" component={Example} onEnter={functionToCheckAuthorization()} />

具有检查授权的功能,例如

function functionToCheckAuthorization(nextState, replace) {
  if (!auth.loggedIn()) {
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

请参阅参考:https://github.com/ReactTraining/react-router/blob/master/examples/auth-flow/app.js

另见参考:https://github.com/ReactTraining/react-router/issues/243,以 auth-flow 为例说明背后的意图

【讨论】:

  • 在我已经在上面的评论中指出这不是我想要的之后,你为什么要发布这个答案。在我的例子中,它恰好是状态的身份验证部分,但它实际上只是一个示例。我想根据状态的任意值有不同的路由模型。
  • 所以澄清一下...您想根据某些价值提供一组不同的路线吗?如果是这种情况,您可以使用上面的方法和一些调整来做到这一点。 auth.loggedIn() 可以替换为您需要检查的任何值。 React 路由器并非设计为在其之上进行状态更改,因此您需要确定路由可见性。 React 路由器和动态路由的常见做法是“......预先声明所有路由,然后像 auth-flow 示例一样验证访问者访问它们的能力。”
猜你喜欢
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多