在安装组件之前进行授权检查的最佳实践是什么?
我使用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 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) => { ... }