【问题标题】:Dynamic Role Based Routing (React-Router)基于动态角色的路由(React-Router)
【发布时间】:2017-07-17 05:00:09
【问题描述】:

我正在构建与电子商务相关的产品,并且有两种类型的用户(客户和卖家)。两种类型的用户都有自己的主页(彼此完全不同)。现在,如果客户已登录,我想在客户主页上路由 /,如果卖家帐户已登录,我想路由到卖家主页。否则它应该路由到登录页面。如何使用react-routerthis boilerplate 实现此功能?

我尝试了如下操作(但没有成功):

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

【问题讨论】:

    标签: javascript reactjs react-router react-boilerplate


    【解决方案1】:

    我正在使用 React Boilerplate 做类似的事情。这是它的要点:

    1. 在 routes.js 中定义一个 onEnter 函数

      onEnter:redirectToLogin, 路径:'/帐户', 名称:'帐户', getComponent(nextState, cb) { ...

    2. routes.js中的导入函数

      导出默认函数 createRoutes(store) { // 使用 getHooks 工厂创建可重用的异步注入器 const { injectSagas, redirectToLogin, redirectToDashboard } = getHooks(store);

    3. app/utils/hooks.js 中创建您的重定向函数。这是您根据用户角色重定向的地方。

      导出函数redirectToLogin(store) { // 设置路径名以启用重定向 设置路径(); 返回(下一个状态,替换)=> { 如果(!用户(商店)){ 代替({ 路径名:'/', 状态:{ nextPathname:nextState.location.pathname } }); } 别的 { if (user(store).account_status === '关闭') { 代替({ 路径名:'/已关闭帐户', 状态:{ nextPathname:nextState.location.pathname } }); } } }; }

    4. app/utils/hooks.js导出重定向函数

      导出函数 getHooks(store) { 返回 { injectReducer:injectAsyncReducer(存储), injectSagas:injectAsyncSagas(存储), redirectToLogin: redirectToLogin(store),

    【讨论】:

    • 但在这种情况下,它不会是同一条路线。让我再解释一下:我有两个主页。一个是给卖家的,另一个是给客户的。用户登录后,它应该路由到其相应的主页。但是 URL 必须相同,即 '/' 我们以 facebook 为例。登录帐户和未登录帐户的登录/主页不同。
    • 啊,如果你想要相同的 url,那么这个解决方案将不会做,因为它只会重定向到例如/customer 或 /seller 基于用户角色。
    【解决方案2】:

    我发现了一篇文章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} />
    

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

    这实质上添加了一个网关检查,该检查适用于您的所有容器,并将根据您的角色指导您。此外,如果您以某种方式点击了错误的 url,它将不允许您访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2012-01-01
      • 1970-01-01
      相关资源
      最近更新 更多