关于react.js:Nextjs-实践从-SSR-到-CSR-的优雅降级

Next.js 是一个十分风行的 React 框架,它提供了开箱即用的服务端渲染(Server-Side Rendering, SSR)能力,咱们能够很轻松地借助 Next.js 实现 SSR,并部署到 Vercel 上。然而,Vercel 在国内没有服务节点,SSR 时通过 Vercel 服务器申请国内的服务接口存在肯定比例的申请失败,影响到了页面的渲染。因而,咱们须要减少客户端渲染(Client-Side Rendering, CSR)的逻辑作为兜底,以晋升渲染成功率。

在 Next.js 中咱们通过给页面组件减少 getServerSideProps 办法,即可触发 SSR。例如,咱们依据页面 URL 上的门路参数 id 调用接口获取详细信息,并将数据提供给页面组件办法渲染。代码如下:

interface Props {
  detail: Detail;
}

async function getServerSideProps(context: GetServerSidePropsContext): Promise<{ props: Props }> {
  const { id } = context.params;
  const detail = await getDetail(id);

  return {
    props: {
      detail,
    },
  };
}

Next.js 会传递 contextgetServerSideProps 办法,其中包含了路由及申请参数信息;咱们通过返回一个蕴含 props 的对象,将获取到的数据通过 props 提供给页面组件在服务端渲染。

const Page: React.FC<Props> = props => {
  return <div>detail 的渲染逻辑 {props.detail}</div>;
};

由此可见,页面组件强依赖了服务端传递 props 的数据,如果申请失败势必导致页面无奈失常渲染。

实现 CSR 的兜底逻辑

首先,咱们须要对 getServerSideProps 进行革新,减少申请出错时的容错:

async function getServerSideProps(context: GetServerSidePropsContext): Promise<{ props: Props | {} }> {
  const { id } = context.params;
  
  try {
    const detail = await getDetail(id);

    return {
      props: {
        detail,
      },
    };
  } catch {
    return {
      props: {},
    };
  }
}

当申请失败时,咱们通过 catch 捕捉到谬误,并将 props 设置为 {},以告诉组件获取数据失败。咱们在组件中利用 useEffect 再次发动申请:

const Page: React.FC<Props> = props => {
  const isEmptyProps = Object.keys(props).length === 0;
  const [detail, setDetail] = useState(props.detail);
  const router = useRouter();

  useEffect(() => {
    if (isEmptyProps) {
      const { id } = router.query;

      getDetail(id).then(props => setDetail(props.detail));
    }
  }, []);

  return <div>detail 的渲染逻辑 {detail}</div>;
};

咱们通过判断 props.detail 是否为空对象,决定是否在浏览器端是否再次发动申请,申请参数 id 能够通过 Next.js 提供的 next/routeruseRouter 获取。数据获取胜利后,保留在组件的 State 中。

至此咱们就实现了页面组件从 SSR 到 CSR 的降级。然而,咱们有很多个页面都须要反对降级,逐个革新的老本太高,咱们须要将这些逻辑进行形象。

形象降级的逻辑

从下面的实现过程来看,降级的逻辑次要分为两步:

  1. getServerSideProps 减少谬误捕捉,出错时 props 返回 {}
  2. 页面组件中判断 props 是否为空对象,如果是则再次发动申请获取数据

针对这两个步骤,咱们能够别离进行形象:

形象 SSR 谬误捕捉

咱们能够通过定义一个工厂函数,用来在原 getServerSideProps 上减少谬误捕捉:

 function createGetServerSidePropsFunction<F = GetServerSideProps>(getServerSideProps: F): F {
    return async (context: GetServerSidePropsContext) => {
      try {
        return await getServerSideProps(context);
      } catch {
        return {
          props: {},
        };
      }
    };
  }

再将这个工厂函数产生的函数导出:

export const getServerSideProps = createGetServerSidePropsFunction(getServerSidePropsOrigin);

形象 CSR 数据申请

咱们能够实现一个高阶组件(Higher-Order Components, HOC)将这部分逻辑形象:

function withCSR<C extends React.FC<any>, P extends object = React.ComponentProps<C>>(component: C, getServerSideProps: GetServerSideProps) {
  const HoC = (props: P) => {
    const [newProps, setNewProps] = useState<P>(props);
    const router = useRouter();
    const isPropsEmpty = Object.keys(props).length === 0;

    useEffect(() => {
      if (isPropsEmpty) {
        const context: GetServerSidePropsContext = {
          locale: router.locale,
          locales: router.locales,
          defaultLocale: router.defaultLocale,
          params: router.query,
          query: router.query,
          resolvedUrl: router.asPath,
          req: {} as unknown,
          res: {} as unknown,
        };

        getServerSideProps(context).then(setNewProps);
      }
    }, []);

    if (newProps) {
      return React.createElement(component, newProps);
    }

    return null;
  };

  HoC.displayName = `Hoc(${component.name})`;

  return HoC;
}

逻辑与后面的实现基本一致,在高阶组件中判断如果 SSR 失败,咱们在浏览器端再次调用 getServerSideProps 发动申请,此时咱们须要结构一个与 Next.js 统一的 context,这里咱们抉择从 next/router 上获取相干信息并结构。最初,咱们将页面组件传入高阶组件,返回一个新的页面组件并导出。

export default withCSR(Page, getServerSidePropsOrigin);

页面组件的接入

实现这两步形象后,咱们的页面组件降级的实现变得非常简单,在不须要批改页面组件和 getServerSideProps 的根底上,只须要减少以下几行:

import { withCSR, getServerSideProps } from '../ssr-fallback';

export const getServerSideProps = createGetServerSidePropsFunction(getServerSidePropsOrigin);

export default withCSR(Page, getServerSidePropsOrigin);

至此,咱们就实现了从 SSR 到 CSR 的优雅降级。

进一步形象成 NPM 包

咱们将以上逻辑形象成了 NPM 包 next-ssr-fallback,并进一步形象了 SSRFallback 类,简化 getServerSideProps 的传递。应用形式如下:

import FallbackSSR from 'next-ssr-fallback';

const fallbackSSR = new FallbackSSR({
  getServerSideProps: getServerSidePropsOrigin,
});

export const getServerSideProps = fallbackSSR.createGetServerSidePropsFunction();

export default fallbackSSR.withCSR(Page);

next-ssr-fallback 的 GitHub 仓库:https://github.com/crazyurus/next-ssr-fallback

这里也有一个接入了 next-ssr-fallback 的 Next.js 我的项目 recruit-pc 供参考,我的项目部署在 Vercel 上 https://recruit-pc.vercel.app

总结

咱们在 Next.js 中遇到了 SSR 渲染失败的问题时,抉择了降级到 CSR 以晋升渲染成功率,并将这部分实现逻辑形象为 next-ssr-fallback 以复用到其它我的项目,实现更为优雅的降级。

如果有其它无关 SSR 降级的实际,欢送分享

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据