Javascript 反应路由器授权
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32898264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Router Authorization
提问by theo
What are the best practices for authorization checking prior to a component mounting?
在组件安装之前进行授权检查的最佳做法是什么?
I use react-router 1.x
我使用反应路由器 1.x
Here are my routes
这是我的路线
React.render((
<Router history={History.createHistory()}>
<Route path="/" component={Dashboard}></Route>
<Route path="/login" component={LoginForm}></Route>
</Router>
), document.body);
Here is my Dashboard component:
这是我的仪表板组件:
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>
);
}
});
回答by Pawel
Updated solution for React router v4
React 路由器 v4 的更新解决方案
<Route
path="/some-path"
render={() => !isAuthenticated ?
<Login/> :
<Redirect to="/some-path" />
}/>
React router up to v3
反应路由器到 v3
Use 'onEnter' event and in callback check if the user is authorized:
使用 'onEnter' 事件并在回调中检查用户是否获得授权:
<Route path="/" component={App} onEnter={someAuthCheck}>
const someAuthCheck = (nextState, transition) => { ... }
回答by Daniel Reina
With react-router 4 you have access to the Route propsinside the component. To redirect a user you just have to push the new URL to the history. In your example, the code would be:
使用 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>
);
}
});
At the docs, they show another way to do it, by using the render
property, instead of component
. They define a PrivateRoute
, that makes the code very explicit when you define all your routes.
在文档中,他们展示了另一种方法,通过使用render
属性而不是component
. 他们定义了一个PrivateRoute
,当你定义所有的路由时,这使得代码非常明确。
回答by Zaman Afzal
If you want to apply authorization on multiple components then you can do it like this.
如果你想对多个组件应用授权,那么你可以这样做。
<Route onEnter={requireAuth} component={Header}>
<Route path='dashboard' component={Dashboard} />
<Route path='events' component={Events} />
</Route>
For single component you can do
对于单个组件,您可以执行
<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')
}