何时使用反应错误边界组件 (react use error boundary)

我们什么时候应该使用错误边界组件?只为缺少道具之类的东西?

我们什么时候应该使用错误边界组件?只为缺少道具之类的东西?

例如,想象一下这个 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} />;
2

我在我的项目中遵循了以下方法,这些方法都是钩子 / 功能组件实现。

我使用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>
   

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(253)
PHP将数组中的项目与同一行中的另一个普通项目相加
上一篇
安装phpapache模块启用sudoapt安装 libapache2-mod-php7.3
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(45条)