介紹
我正在處理我的應用程式中的所有錯誤。我注意到在 React 中可以處理不同型別的錯誤......
渲染錯誤(未定義的道具,...),可以使用Error Boundary Component和自定義 Fallback Components 處理。
來自后端的錯誤,我想在帶有 i18n.js 的 toast 中顯示以翻譯訊息。
在 React 應用程式中結合這兩種型別的錯誤處理是否常見?
在吐司中顯示錯誤
我決定創建自己的React Context,為通知、錯誤等呈現 Toast。這是我的實作:
/* eslint-disable react/prop-types */
import React, {
createContext,
useReducer,
useMemo,
} from "react";
import toastReducer, {
initialState,
actionCreators,
} from "./helpers/reducers/toastReducer";
import { TOAST_TYPES, DEFAULT_TOAST_DURATION } from "../../utils/toast";
import Toast from "../../components/Toast";
const ToastContext = createContext(null);
export default ToastContext;
export function ToastProvider({ children }) {
const [toast, dispatch] = useReducer(toastReducer, initialState);
const open = (
type = TOAST_TYPES[0],
message,
duration = DEFAULT_TOAST_DURATION,
action = undefined
) => {
dispatch(actionCreators.open(type, message, duration, action));
};
const close = () => {
dispatch(actionCreators.close());
};
const value = useMemo(() => ({
open,
close,
}), []);
return (
<ToastContext.Provider value={value}>
{children}
<Toast
visible={toast.visible}
type={toast.type}
duration={toast.duration}
action={toast.action}
onDismiss={close}
>
{toast.message}
</Toast>
</ToastContext.Provider>
);
}
我還實作了使用此背景關系的 useToast() 鉤子。
從服務器獲取資料
當我使用鉤子時,我將錯誤保存在每個從我的資料庫獲取資料的自定義鉤子上的“錯誤”狀態中。
// Based on the library "useQuery"
const useFetchSomeData = ({ fetchOnMount = true } = {}) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const cursor = useRef(new Date());
const isFetching = useRef(false);
const fetchData = async () => {
if (isFetching.current) return;
isFetching.current = true;
setLoading(true);
try {
const data = await api.fetchData(cursor.current);
} catch(err) {
setError(err);
} finally {
setLoading(false);
isFetching.current = false;
}
}
useEffect(() => {
if (fetchOnMount) {
fetchData();
}
}, []);
return {
data,
loading,
error,
fetchData
}
}
And in my components I just do:
const { data, error, loading } = useFetchData();
const toast = useToast();
const { t } = useI18N();
useEffect(() => {
if (error) {
toast.open("error", t(err.code));
}
}, [error, t]);
Questions
As you can see, in my components, I am just using a
useEffectfor sending the translated errors to my toast context. But... what if I get the same error response from the server twice? I mean, the error is not reset tonullin the custom hook... how can I do that?Is this implementation robust (in your opinion) and typical in these situations?
uj5u.com熱心網友回復:
老實說,我有點困惑,我想我明白您要做什么,但不必如此復雜。
你應該用一個ToastContainer或ToastContext(無論你想怎么稱呼它)包裝你的整個應用程式并在需要時匯入你的toast然后呼叫Toat.show("Error: ..."). 查看圖書館react-toastify了解更多詳細資訊,也許這個圖書館可以幫助你。您將專案包裝在應用程式入口級別,再也不用擔心了。
就錯誤處理而言,在創建函式來獲取資料時,您應該期望一次出現一個錯誤并進行適當的處??理。我個人認為最好將錯誤回傳給呼叫 fetch 函式的原始組件并在那里處理它。在我看來,以這種方式跟蹤事情更容易,但你所做的并沒有錯。
錯誤處理需要時間和提前思考,我不會否認這一點,但它在構建不良的應用程式和經過深思熟慮的應用程式之間產生了很大的不同。
我也不完全確定你為什么const isFetching = useRef(false);在你可以使用的時候使用const [isFetching, setIsFecthing] = useState(false),這就是為什么useState。對于useMemo. 我認為這里的事情可能會更精簡,隨著您的應用程式的增長和變得更加復雜,它會更容易維護。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/367201.html
標籤:reactjs react-native error-handling react-hooks try-catch
