【问题标题】:How to protected routes on client side in Nextjs and redirect if don't have admin role?如果没有管理员角色,如何在 Nextjs 中保护客户端的路由并重定向?
【发布时间】:2020-09-26 10:59:18
【问题描述】:

现在,我在 Context 中拥有用户角色。如果用户没有管理员角色,我可以在获取数据之前检查每个页面上 useEffect 中上下文的角色并重定向到登录:

useEffect(() => {
    if (userInfo.role == 2) {
        getPosts(pagerInfo.currentPage);
    } else {
        Router.push('/login');
    }
    
}, []);

但我不想重写以检查每个页面上的用户角色。如何在每个页面上使用它?

【问题讨论】:

    标签: reactjs authentication next.js


    【解决方案1】:

    在顶级组件中执行一次,例如_app.js

    【讨论】:

      【解决方案2】:

      您必须编写一个更高阶的组件,该组件将组件作为参数,您应用一些条件并根据满足的条件允许或拒绝访问。

      const withAuth = (Component) => (role) => {
        // those props will be passed to HOC when you use this. 
        return (props) => {
          //here you write your code to get the data
          if (userInfo.role == 2) {
              return <Component user={data} loading={loading} {...props} />;
      
         } else {
            Router.push('/login');
         }      
        };
      };
      

      您的某些页面将是公开的,而其中一些将是私有的。所以将私有页面连接到这个 HOC。

      // i pass two props to show how to use them
      const OnlyAdmin = ({user, loading}) => {
        return (
          <BaseLayout  loading={loading}>      
            <h1>I am Admin Page - Hello {user.name}</h1>
          </BaseLayout>
        )
      }
      
      export default withAuth(OnlyAdmin)('admin');
      

      【讨论】:

      • 我试过了,但是得到一个错误:TypeError: Cannot read property 'join' of undefined 你可以在这里看到:imgur.com/a/rcsLvLd
      • 您可以在这里查看详细信息:github.com/vercel/next.js/discussions/17397
      • "children" 未定义,因为您没有将道具传递给组件。 const AdminPublishedPosts: NextPage = (PROPSSSS) => { return ( ); };
      • 那么,通过道具后我会做点什么吗? ('props' 被声明但它的值从未被读取)
      猜你喜欢
      • 1970-01-01
      • 2017-09-11
      • 2021-10-10
      • 2015-07-29
      • 1970-01-01
      • 2014-07-18
      • 2015-11-09
      • 1970-01-01
      • 2021-07-19
      相关资源
      最近更新 更多