你如何处理 NextJS 应用程序中的公共和私有路由?

Wil*_*eto 10 reactjs next.js

我正在开发一个应用程序,我们有公共和管理路由,在我们过去的 CRA 应用程序中,我们使用了自定义路由元素,但我们在 nextjs 中没有……我们有很多公共页面,我们有 20 个私人页面/路线。

在nextjs中处理受保护的认证路由和公共路由的最佳方法是什么?

非常感谢!最好的事物

Ale*_*iuS 16

我个人一直为此使用 HOC(高阶组件)。

这是一个示例身份验证 HOC:

const withAuth = Component => {
  const Auth = (props) => {
    // Login data added to props via redux-store (or use react context for example)
    const { isLoggedIn } = props;

    // If user is not logged in, return login component
    if (!isLoggedIn) {
      return (
        <Login />
      );
    }

    // If user is logged in, return original component
    return (
      <Component {...props} />
    );
  };

  // Copy getInitial props so it will run as well
  if (Component.getInitialProps) {
    Auth.getInitialProps = Component.getInitialProps;
  }

  return Auth;
};

export default withAuth;
Run Code Online (Sandbox Code Playgroud)

您可以将此 HOC 用于任何页面组件。下面是一个使用示例:

const MyPage = () => (
  <> My private page</>
);

export default withAuth(MyPage);
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以使用角色检查(如公共、普通用户和管理员)扩展 withAuth HOC。

  • 这是行不通的。 (3认同)

Put*_*txe 5

非常感谢@AleXiuS 您的回答!我将您的解决方案和这篇精彩的文章混合在一起,供那些想要将此临时文件与打字稿一起使用的人使用:

import { NextComponentType } from "next";

function withAuth<T>(Component: NextComponentType<T>) {
  const Auth = (props: T) => {
    // Login data added to props via redux-store (or use react context for example)
    const { isLoggedIn } = props;

    // If user is not logged in, return login component
    if (!isLoggedIn) {
      return <Login />;
    }

    // If user is logged in, return original component
    return <Component {...props} />;
  };

  // Copy getInitial props so it will run as well
  if (Component.getInitialProps) {
    Auth.getInitialProps = Component.getInitialProps;
  }

  return Auth;
}

export default withAuth;
Run Code Online (Sandbox Code Playgroud)