簡體   English   中英

基於動態角色的路由(反應路由器)

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

我正在開發與電子商務相關的產品,並且有兩種類型的用戶(客戶和賣方)。 兩種類型的用戶都有自己的主頁(彼此完全不同)。 現在,如果客戶已登錄,我想在客戶主頁上路由/,如果賣家帳戶已登錄,我要路由到賣家主頁。 否則,它應該轉到目標網頁。 如何使用react-router此樣板實現此功能?

我嘗試執行以下操作(但沒有成功):

{
      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);
      },
    }, 

我正在使用React Boilerplate做類似的事情。 這是要點:

  1. 在routes.js中定義一個onEnter函數

    onEnter:redirectToLogin,路徑:'/ account',名稱:'account',getComponent(nextState,cb){...

  2. routes.js導入功能

    導出默認函數createRoutes(store){//使用getHooks工廠常量創建可重復使用的異步注入器{injectSagas,redirectToLogin,redirectToDashboard} = getHooks(store);

  3. app/utils/hooks.js創建重定向功能。 您可以在此處根據用戶角色進行重定向。

    導出函數redirectToLogin(store){//設置路徑名以啟用重定向setPath(); 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}}); }}}; }

  4. app/utils/hooks.js導出重定向功能

    導出函數getHooks(store){return {injectReducer:injectAsyncReducer(store),injectSagas:injectAsyncSagas(store),redirectToLogin:redirectToLogin(store),

我在這里找到了一篇文章,要點是在這里寫的。 您可以像這樣向組件添加道具

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

然后在您的組件中添加以下代碼,該代碼在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

從本質上講,這將添加一個網關檢查,該檢查將在所有容器上起作用,並根據您的角色指導您。 此外,如果您以某種方式輸入了錯誤的網址,它也將不允許您訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM