我找到一篇文章here,我在这里写的要点。 您可以将道具添加到您组件像这样
<Route path="/" component={App}>
//BOD routes
<Route authorisedUsers={['KR']} path="/home" component={HomeContainer} />
//HR routes
<Route authorisedUsers={['HR']} path="/hrhome" component={HRDashboardContainer} />
//common routes
<Route authorisedUsers={['KR', 'HR']} path="/notes" component={NotesContainer} />
,然后添加在组件下面的代码,呈现在路径=“/”
Role based routing react redux
componentDidUpdate() {
const {
children, //Component to be rendered (HomeContainer if route = '/home')
pathname: {location}, //location.pathname gives us the current url user is trying to hit. (with react router)
profileId, //profileId required by profile page common to all user journeys.
role } = this.props;
this.reRoute(role, this.props.children, location.pathname, ProfileId)
}
decideRoute(role, ProfileId) { //decide routes based on role
if(role==='HR')
return 'hrhome';
else if(role==='KR')
return 'home';
else if(role==='USER'&&ProfileId)
return 'profile/'+ProfileId;
else
return '/error';
}
isAuthorised(authorisedUsers, role) {
return _.includes(authorisedUsers, role)
}
reRoute(role, children, path, ProfileId) {
if(role===null && path!=='/') // user hit a different path without being authenticated first
{
hashHistory.replace('/'); //this is where we implemented login
return;
}
let route = this.decideRoute(role, ProfileId) //if role has already been fetched from the backend, use it to decide the landing page for each role.
if(children) // if we already are on one of the user journey screens ...
{
const authorisedUsers = children.props.route.authorisedUsers
if(!this.isAuthorised(authorisedUsers,role)) //... and the user is not allowed to view this page...
hashHistory.replace(`/${route}/`); //... redirect him to the home page corresponding to his role.
}
else
hashHistory.replace(`/${route}/`); // if the user has just logged in(still on/page or login page), and we know his role, redirect him to his home page.
}//if none of these holds true, user is allowed to go ahead and view the page
这实质上增加一个网关检查,可以在你的所有容器上工作,并根据你的角色指导你。此外,它不会让你访问,如果你不知何故击中了错误的网址。
但是在这种情况下,它将不会是相同的路线。让我再次向你解释:我有两个主页。一个是卖方,另一个是卖方。用户登录后,应该路由到相应的主页。但URL必须相同,即'/' 让我们以facebook为例。登录/主页对于登录和未登录帐户是不同的。 –
啊,如果你想要相同的网址,那么这个解决方案将无法完成,因为它只会重定向到例如/ customer或/ seller根据用户角色。 – Kunal