使用React.lazy()时开发版本会崩溃

时间:2019-09-19 06:12:26

标签: reactjs react-router react-hooks

我正在使用React Lazy和Suspense加载组件,但是如果我尝试使用 npm run build 来构建应用程序,则会收到一条错误消息,提示错误:未捕获的错误:缩小的React错误#294; ,并且如果我评论延迟加载,则构建成功。 代码:

import { Suspense, lazy } from 'react';
const Component= lazy(() => import('./../location'));

const Homepage=()=>{
  return (
    <>
      <Suspense fallback={<div>Loading...</div>}>                
        <Component/>
      </Suspense>
    </>
  )
}
export default Homepage;

2 个答案:

答案 0 :(得分:1)

当我们使用ssr(服务器端渲染)或ReactDOMServer时,此错误基本上会在路径中出现

由于ReactDOMServer尚不支持React.lazy和Suspense,因此您需要使用动态导入并删除Suspense和React.lazy以避免此错误。

答案 1 :(得分:1)

要解决此问题,必须在前面加载Suspense组件。下一个示例仅在存在window变量的情况下,使用useEffect放在Suspense组件上。仅在浏览器中使用window变量。

export const GuardLazyComponentToSSR: FunctionComponent = () => {
    const [isFront, setIsFront] = useState(false);

    useEffect(() => {
        process.nextTick(() => {
            if (globalThis.window ?? false) {
                setIsFront(true);
            }
        });
    }, []);

    if (!isFront) return null;

    return <Suspense fallback={() => 'loading'}>
        <MyLazyComponent></MyLazyComponent>
    </Suspense>;
}