简体   繁体   English

基于动态角色的路由(反应路由器)

[英]Dynamic Role Based Routing (React-Router)

I am building an e-commerce related product and there are two types of users (customer & seller). 我正在开发与电子商务相关的产品,并且有两种类型的用户(客户和卖方)。 Both types of user have their own homepage (totally different to each other). 两种类型的用户都有自己的主页(彼此完全不同)。 Now I want to route / on customer homepage if customer is logged-in or to seller homepage if seller account is logged-in. 现在,如果客户已登录,我想在客户主页上路由/,如果卖家帐户已登录,我要路由到卖家主页。 Otherwise it should route to landing page. 否则,它应该转到目标网页。 How can I achieve this feature using react-router and this boilerplate ? 如何使用react-router此样板实现此功能?

I tried to do something as follows (but it didn't work): 我尝试执行以下操作(但没有成功):

{
      path: '/',
      name: 'home',
      getComponent(nextState, cb) {
        let HomePagePath = 'containers/HomePage';
        if (customerLoggedIn) {
            HomePagePath = 'containers/CustomerHomePage';
       }
        const importModules = Promise.all([
          import(HomePagePath),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([component]) => {
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, 

I'm using React Boilerplate to do something similar. 我正在使用React Boilerplate做类似的事情。 Here's the gist of it: 这是要点:

  1. Define an onEnter function in routes.js 在routes.js中定义一个onEnter函数

    onEnter: redirectToLogin, path: '/account', name: 'account', getComponent(nextState, cb) { ... onEnter:redirectToLogin,路径:'/ account',名称:'account',getComponent(nextState,cb){...

  2. Import function in routes.js routes.js导入功能

    export default function createRoutes(store) { // Create reusable async injectors using getHooks factory const { injectSagas, redirectToLogin, redirectToDashboard } = getHooks(store); 导出默认函数createRoutes(store){//使用getHooks工厂常量创建可重复使用的异步注入器{injectSagas,redirectToLogin,redirectToDashboard} = getHooks(store);

  3. Create your redirect function in app/utils/hooks.js . app/utils/hooks.js创建重定向功能。 This is where you'd redirect based on user role. 您可以在此处根据用户角色进行重定向。

    export function redirectToLogin(store) { // set pathname to enable redirect setPath(); 导出函数redirectToLogin(store){//设置路径名以启用重定向setPath(); return (nextState, replace) => { if (!user(store)) { replace({ pathname: '/', state: { nextPathname: nextState.location.pathname } }); return(nextState,replace)=> {if(!user(store)){replace({pathname:'/',state:{nextPathname:nextState.location.pathname}}); } else { if (user(store).account_status === 'closed') { replace({ pathname: '/closedaccount', state: { nextPathname: nextState.location.pathname } }); } else {if(user(store).account_status ==='closed'){replace({pathname:'/ closedaccount',state:{nextPathname:nextState.location.pathname}}); } } }; }}}; } }

  4. Export redirect function from app/utils/hooks.js app/utils/hooks.js导出重定向功能

    export function getHooks(store) { return { injectReducer: injectAsyncReducer(store), injectSagas: injectAsyncSagas(store), redirectToLogin: redirectToLogin(store), 导出函数getHooks(store){return {injectReducer:injectAsyncReducer(store),injectSagas:injectAsyncSagas(store),redirectToLogin:redirectToLogin(store),

I found an article here , the gist of which i am writing here. 我在这里找到了一篇文章,要点是在这里写的。 You can add a prop to you component like so 您可以像这样向组件添加道具

<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} />

and then add the following code in your component, that renders on path='/' 然后在您的组件中添加以下代码,该代码在path ='/'上呈现

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

This essentially adds a gateway check that would work on all your containers and will direct you based on your role. 从本质上讲,这将添加一个网关检查,该检查将在所有容器上起作用,并根据您的角色指导您。 Also, it wont allow you access if you somehow hit the wrong url. 此外,如果您以某种方式输入了错误的网址,它也将不允许您访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM