我們什么時候應該使用錯誤邊界組件?只是因為缺少道具和類似的東西?
例如,想象一下這個 api 獲取鉤子:
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} />;
uj5u.com熱心網友回復:
我在我的專案中遵循了以下方法,這些方法都是鉤子/功能組件實作。
我正在使用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的根index.tsx檔案包裝在一個ErrorBoundary. 所以,我的代碼看起來更像這樣
...
<ErrorBoundary FallbackComponent={ErrorFallback}>
<SWRConfig ...>
<React.StrictMode>
<ScrollToTop></ScrollToTop>
<App ... />
</React.StrictMode>
</SWRConfig>
</ErrorBoundary>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405736.html
標籤:
