反应路由器授权

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

我使用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>
    );
  }
});
阿飞番长2020/03/19 11:41:10

更新了React Router v4的解决方案

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

反应路由器到v3

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

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

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