【问题标题】:Development build crashes when using React.lazy()使用 React.lazy() 时开发构建崩溃
【发布时间】:2020-01-20 02:47:19
【问题描述】:

我正在使用 react Lazy 和 Suspense 来加载组件,但是如果我尝试使用 npm run build 构建应用程序,我会收到一条错误消息 Error: Uncaught Error: Minified 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;

【问题讨论】:

标签: reactjs react-router react-hooks


【解决方案1】:

这个错误基本上是在我们使用ssr(服务器端渲染)或ReactDOMServer时发生的,

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

【讨论】:

  • 这真的很伤心
【解决方案2】:

要解决这个问题,必须在前面加载 Suspense 组件。下一个示例使用useEffect 仅在存在 window 变量的情况下将其放在 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>;
}

【讨论】:

    【解决方案3】:

    如果其他人遇到这个问题,有几种解决方案。

    如果你正在使用 next.js 并尝试使用 React.Suspense,你可能会遇到这个错误。在 Next.js 中,你可以简单地使用内置的next/dynamic 来解决这个问题。

    Next.js 注意:在 import('path/to/component') 中,路径必须显式 书面。不能是模板字符串,也不能是变量。

    所以here 是在需要变量导入路径时使用它的示例。

    如果由于某种原因您需要完全使用 React.Suspense,您可以使用上面@JonDotsoy 的答案之类的解决方案,或者您可以创建一个类似的钩子:

    const useMounted = () => {
        const [ hasMounted, setHasMounted ] = useState(false);
    
        useEffect(() => setHasMounted(true), []);
    
        return { hasMounted };
    };
    

    并像这样使用它:

    const Component = () => {
        
        const { hasMounted } = useMounted()
    
        const LazyComponent = React.lazy(() => import('./path/to/component'))
    
        
        return !hasMounted ? <div>Some fallback</div> : <LazyComponent />
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2023-03-27
      • 2023-03-27
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      相关资源
      最近更新 更多