我们什么时候应该使用错误边界组件?只是为了丢失 Prop 之类的东西?
例如,想象一下这个 api 获取钩子(Hook):
const useFetch = () => {
...
const [error, setError] = useState(null);
const method = async () => {
try {
await api.fetchData();
} catch(err) {
setError(err);
}
};
useEffect(() => {
method();
},[]);
return { ..., error };
}
现在,在组件中,我只需执行以下操作:
const MyComponent = () => {
const { error } = useFetch();
if (error) return <FallbackUI />;
return <MainUI />;
}
我可以使用 ErrorBoundary 组件来处理这种情况(API 调用错误)而不是条件渲染吗?
编辑
如果我只想在获取数据方法失败并且之前检索过任何数据时显示后备 UI,该怎么办?
类似于:
const { data, getMoreData, error } = useFetchPosts(); // data is stateful inside the hook
if (error && !data) return <FallbackUI />;
return <MainUI data={data} />;
最佳答案
我在我的项目中遵循了以下方法,这些方法都是钩子(Hook)/功能组件实现。
我正在使用https://github.com/bvaughn/react-error-boundary
import { ErrorBoundary } from "react-error-boundary";
<ErrorBoundary FallbackComponent={ErrorFallback}>
<MyComponent />
</ErrorBoundary>
//reject the promise so it gets bubbled up
const useFetch = () => {
...
const [error, setError] = useState(null);
const method = async () => {
try {
await api.fetchData();
} catch(err) {
// setError(err);
return Promise.reject(err);
}
};
useEffect(() => {
method();
},[]);
return { ..., error };
}
function ErrorFallback({ error }: { error: any }) {
return (
<>
// you custom ui you'd like to return
</>
);
}
编辑:
我通常将其放在顶层,因此这通常是所有未处理异常的捕获。换句话说,我将 App.tsx
包装在 ErrorBoundary
的根 index.tsx
文件中。所以,我的代码看起来更像这样
...
<ErrorBoundary FallbackComponent={ErrorFallback}>
<SWRConfig ...>
<React.StrictMode>
<ScrollToTop></ScrollToTop>
<App ... />
</React.StrictMode>
</SWRConfig>
</ErrorBoundary>
关于javascript - 何时使用 React 错误边界组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70621393/