the*_*heo 60 javascript authorization reactjs react-router
在组件安装之前进行授权检查的最佳做法是什么?
我使用react-router 1.x
这是我的路线
React.render((
<Router history={History.createHistory()}>
<Route path="/" component={Dashboard}></Route>
<Route path="/login" component={LoginForm}></Route>
</Router>
), document.body);
Run Code Online (Sandbox Code Playgroud)
这是我的仪表板组件:
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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
Paw*_*wel 64
针对React路由器v4的更新解决方案
<Route
path="/some-path"
render={() => !isAuthenticated ?
<Login/> :
<Redirect to="/some-path" />
}/>
Run Code Online (Sandbox Code Playgroud)
使路由器达到v3
使用'onEnter'事件并在回调中检查用户是否获得授权:
<Route path="/" component={App} onEnter={someAuthCheck}>
const someAuthCheck = (nextState, transition) => { ... }
Run Code Online (Sandbox Code Playgroud)
使用react-router 4,您可以访问组件内的Route道具.要重定向用户,您只需将新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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
在文档中,他们通过使用属性而不是使用属性来显示另一种方法.它们定义了一个,当您定义所有路由时,它会使代码非常明确.rendercomponentPrivateRoute