反应路由器授权

React Router Authorization

在安装组件之前进行授权检查的最佳做法是什么?

我用的是react-router 1.x

这是我的路线

React.render((
  <Router history={History.createHistory()}>
    <Route path="/" component={Dashboard}></Route>
    <Route path="/login" component={LoginForm}></Route>
  </Router>
), document.body);

这是我的仪表板组件:

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>
    );
  }
});

更新解决方案 React 路由器 v4

<Route 
  path="/some-path" 
  render={() => !isAuthenticated ?
    <Login/> :
    <Redirect to="/some-path" />
}/>

React 路由到 v3

使用 'onEnter' 事件并在回调中检查用户是否被授权:

<Route path="/" component={App} onEnter={someAuthCheck}>  

const someAuthCheck = (nextState, transition) => { ... }

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

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,当你定义你所有的路由时,这使得代码非常明确。

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

<Route onEnter={requireAuth} component={Header}>
    <Route path='dashboard' component={Dashboard} />
    <Route path='events' component={Events} />
</Route>

对于单个组件,您可以执行

<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')
}