【问题标题】:Place getServerSideProps function in an helper将 getServerSideProps 函数放在帮助程序中
【发布时间】:2021-08-10 04:59:59
【问题描述】:

我有很多页面需要使用 firebase 管理方法来保护:

const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
  try {
    const cookies = nookies.get(ctx);
    const token = await firebaseAdmin.auth().verifyIdToken(cookies.token);
    const { uid, email } = token;

    return {
      props: {
        email,
        uid,
      },
    };
  } catch (err) {
    return {
      redirect: {
        permanent: false,
        destination: "/",
      },
      props: {} as unknown as never,
    };
  }
};

const ExpertPage = (
  props: InferGetServerSidePropsType<typeof getServerSideProps>,
) => {
  return (
    <Layout type={ILayoutType.EXPERT}>
      <ProtectedPage1 props={props} />
    </Layout>
  );
};

export default ExpertPage;

如您所见,应该在所有这些页面上调用函数 getServerSideProps,这是我想避免的。

我试图将它移动到一个助手中,以便在此处将其称为类型InferGetServerSidePropsType&lt;typeof getServerSideProps&gt;

但它没有运行。我想知道是否有更好的方法。

【问题讨论】:

标签: reactjs typescript next.js


【解决方案1】:

只需从页面重新导出即可:

// utils/commonGetServerSideProps.ts

const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
  try {
    const cookies = nookies.get(ctx);
    const token = await firebaseAdmin.auth().verifyIdToken(cookies.token);
    const { uid, email } = token;

    return {
      props: {
        email,
        uid,
      },
    };
  } catch (err) {
    return {
      redirect: {
        permanent: false,
        destination: "/",
      },
      props: {} as unknown as never,
    };
  }
};

export default getServerSideProps;
// pages/expert.tsx

const ExpertPage = (
  props: InferGetServerSidePropsType<typeof getServerSideProps>,
) => {
  return (
    <Layout type={ILayoutType.EXPERT}>
      <ProtectedPage1 props={props} />
    </Layout>
  );
};

export default ExpertPage;


export { default as getServerSideProps } from "../utils/commonGetServerSideProps"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2022-10-24
    相关资源
    最近更新 更多