首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >React路由器授权

React路由器授权
EN

Stack Overflow用户
提问于 2015-10-02 07:18:27
回答 2查看 42.3K关注 0票数 65

在挂载组件之前进行授权检查的最佳实践是什么?

我使用react-router 1.x

以下是我的路线

代码语言:javascript
复制
React.render((
  <Router history={History.createHistory()}>
    <Route path="/" component={Dashboard}></Route>
    <Route path="/login" component={LoginForm}></Route>
  </Router>
), document.body);

这是我的仪表板组件:

代码语言:javascript
复制
var Dashboard = React.createClass({
  componentWillMount: function () {
    // I want to check authorization here
    // If the user is not authorized they should be redirected to the login page.
    // What is the right way to perform this check?
  },

  render: function () {
    return (
      <h1>Welcome</h1>
    );
  }
});
EN

回答 2

Stack Overflow用户

发布于 2017-04-11 00:09:32

使用react-router 4,您可以访问组件内部的Route props。要重定向用户,您只需将新URL推送到历史记录。在您的示例中,代码为:

代码语言:javascript
复制
var Dashboard = React.createClass({
  componentWillMount: function () {
    const history = this.props.history; // you'll have this available
    // You have your user information, probably from the state
    // We let the user in only if the role is 'admin'
    if (user.role !== 'admin') {
      history.push('/'); // redirects the user to '/'
    }
  },

  render: function () {
    return (
      <h1>Welcome</h1>
    );
  }
});

在文档中,他们通过使用render属性而不是component来显示another way to do it。它们定义了一个PrivateRoute,当您定义所有路由时,这使得代码非常明确。

票数 6
EN

Stack Overflow用户

发布于 2017-08-18 19:04:18

如果你想在多个组件上应用授权,你可以这样做。

代码语言:javascript
复制
<Route onEnter={requireAuth} component={Header}>
    <Route path='dashboard' component={Dashboard} />
    <Route path='events' component={Events} />
</Route>

对于单个组件,您可以这样做

代码语言:javascript
复制
<Route onEnter={requireAuth} component={Header}/>

function requireAuth(nextState, replaceState) {
  if (token || or your any condition to pass login test)
  replaceState({ nextPathname: nextState.location.pathname }, 
  '/login')
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32898264

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档