在挂载组件之前进行授权检查的最佳实践是什么?
我使用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>
);
}
});
发布于 2017-04-11 00:09:32
使用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
,当您定义所有路由时,这使得代码非常明确。
发布于 2017-08-18 19:04:18
如果你想在多个组件上应用授权,你可以这样做。
<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')
}
https://stackoverflow.com/questions/32898264
复制相似问题