我有一个动态加载组件的函数如下:
export const loader = (file: string) => {
let pagePath = file.replace(/^views/, 'pages');
pagePath = pagePath.replace(/\/index$/, '');
const LazyComponent = lazy(
() =>
import(
/* webpackChunkName: "dynamic_page" */ `@/${pagePath}/index.tsx`
),
);
return (
<Suspense fallback={<Loading />}>
<LazyComponent />
</Suspense>
);
};
export const Loader: React.FC<{ path: string }> = ({ path }) => {
return (
<ErrorBoundary>
{loader(path)}
</ErrorBoundary>
);
};
Run Code Online (Sandbox Code Playgroud)
当传递错误的路径时,动态导入部分会抛出错误:
caught Error: Cannot find module './pages/modules/info/priceConfig/index.tsx'
Run Code Online (Sandbox Code Playgroud)
为什么 ErrorBoundary 组件不处理错误?如果我想捕获它并返回默认组件,该怎么办?
小智 7
为什么 ErrorBoundary 组件不处理错误?
ErrorBoundary 处理渲染、生命周期方法期间 React 组件树中抛出的错误。它不会捕获异步代码中引发的错误,例如 Promises。
这里建议了一种解决方法: https://eddiewould.com/2021/28/28/handling-rejected-promises-error-boundary-react/
您的问题的解决方案:
const LazyComponent = lazy(() =>
import...).catch(
(error) => {
console.error("Component Failed Loading:", error);
return { default: FallbackComponent };
}
)
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2575 次 |
最近记录: |