如何在盖茨比中使用React

如何在盖茨比中使用React

本文介绍了如何在盖茨比中使用React.lazy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像在盖茨比中使用React.lazy一样,制作production(gatsby build)时会出错,在盖茨比项目中使用React.lazysuspense的最佳方法是什么

As using React.lazy in Gatsby you'll get error when making production( gatsby build), what is the best way to use React.lazy and suspense in Gatsby Project

推荐答案

React.lazy和Suspense尚未为服务器端呈现做好准备,但仍可以通过检查代码是否仅在客户端上执行来使用它们.尽管此解决方案不如可加载组件(在服务器端和客户端均可使用),但它仍提供了处理仅客户端包的替代方法,而没有增加依赖性.请记住,如果在没有isSSR防护的情况下执行以下代码,则它们可能会中断.

React.lazy and Suspense are still not ready for server-side rendering, but they can still be used by checking that the code is executed only on the client. While this solution is inferior to loadable-components, that works both on server side and client, it still provides an alternative for dealing with client-side only packages, without an added dependency. Remember that the following code could break if executed without the isSSR guard.

import React from "react"
const ClientSideOnlyLazy = React.lazy(() =>
  import("../components/ClientSideOnly")
)
const MyPage = () => {
  const isSSR = typeof window === "undefined"
  return (
    <>
      {!isSSR && (
        <React.Suspense fallback={<div />}>
          <ClientSideOnlyLazy />
        </React.Suspense>
      )}
    </>
  )
}

必须遵守此行会,以防不行为你

这篇关于如何在盖茨比中使用React.lazy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 10:06