Reactjs 使用React.lazy()时开发构建崩溃

Reactjs 使用React.lazy()时开发构建崩溃,reactjs,react-router,react-hooks,Reactjs,React Router,React Hooks,我正在使用react Lazy and Suspence加载组件,但如果我尝试使用npm run build构建应用程序,我会收到一个错误,错误是错误:未捕获错误:缩小的react错误#294,并且如果我对延迟加载进行注释,则构建会成功。 代码: 从'react'导入{suspent,lazy}; const Component=lazy(()=>import('./../location'); const主页=()=>{ 返回( ) } 导出默认主页; 当我们使用ssr(服务器端渲染)或Rea

我正在使用react Lazy and Suspence加载组件,但如果我尝试使用npm run build构建应用程序,我会收到一个错误,错误是错误:未捕获错误:缩小的react错误#294,并且如果我对延迟加载进行注释,则构建会成功。 代码:

从'react'导入{suspent,lazy};
const Component=lazy(()=>import('./../location');
const主页=()=>{
返回(
)
}
导出默认主页;

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


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

要解决此问题,必须在前端加载Suspend组件。下一个示例仅当存在窗口变量时,才使用
useffect
在悬念组件上显示。窗口变量仅在浏览器中使用

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>;
}
导出常量GuardLazyComponentToSSR:FunctionComponent=()=>{
const[isFront,setIsFront]=useState(false);
useffect(()=>{
process.nextTick(()=>{
如果(全局此窗口??错误){
setIsFront(真);
}
});
}, []);
如果(!isFront)返回null;
返回“正在加载”}>
;
}

我认为这是因为React。lazy和Suspend还不能用于服务器端渲染。ReactDOMServer还不支持Suspend。这真是令人伤心
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>;
}