【问题标题】:With react-router is ite possible to access context from a Route's onEnter prop?使用 react-router 是否可以从 Route 的 onEnter 属性访问上下文?
【发布时间】:2016-09-08 20:03:40
【问题描述】:

我正在研究如何根据上下文中的用户权限级别控制哪些路由可用。

我找到了a nice example,但它依赖于 localStorage 来存储用户身份验证状态。我宁愿保持一切“状态”。 我已经玩了一段时间了,但我似乎无法将上下文传递给<Route ... />onEnter() 道具。我最接近的解决方案看起来非常糟糕,我开始认为让 react-router 了解上下文是一个糟糕的策略。

有人举个例子吗?或者可以确认路由器不应该根据上下文做出决定?

谢谢

编辑:我已经指出了 react-router 示例,它看起来很有希望:https://github.com/reactjs/react-router/tree/master/examples

【问题讨论】:

  • 我正在使用反应路由器并利用 onEnter 允许用户根据他们的身份验证和访问级别访问不同的路由。这很好用。我通常这样做onEnter={ RouterMiddleware.authenticatedUsersOnly },如果我需要通过商店,我使用这个onEnter={ (nextState, replace) => { RouterMiddleware.loginLevel(nextState, replace, store) } } 您可以查看反应路由器文档以检查是否以及如何访问其中间件中的上下文。 * 处理用户请求时不要忘记处理认证+权限级别服务器端。

标签: reactjs react-router


【解决方案1】:

虽然localStorage 相当可靠,但它可能不受支持或用户可以删除它。

我建议您改用redux & react-redux,然后您可以轻松访问应用程序的state,代码如下所示:

const Root = ({ store }) => (

  function authenticateUser(nextState, replaceState, callback) {
     const state = store.getState()
     // do your thing - forbid, grant access etc...
  }

  <Provider store={store}>
    <Router>
      <Route path="/" component={App} onEnter={authenticateUser} />
    </Router>
  </Provider>
);

此外,redux 可帮助您扩展 react 应用程序。起初理解redux 可能有点困难和难以理解,但没关系 - 因为努力是值得的,并且会得到回报。 Usage of redux with react-router.

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 2016-07-22
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2020-08-22
    • 2017-09-04
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多