在我的功能組件/頁面中,我有一個常量/函式,我將錯誤訊息傳遞給它,然后更新幾個 useState 記錄并將錯誤記錄到控制臺。它看起來像這樣:
const catchError = (e:any, message:string) => {
//throw new Error(e)
setMessage(message);
setLoading(false);
console.error(e);
};
我想將此代碼移動到一個鉤子(?)/幫助檔案,這將允許我將其匯入任何其他組件。這意味著我可以使用一段集中的代碼而不是在多個地方撰寫相同的代碼并避免相關問題。
因此,我創建了一個catchError.tsx包含以下內容的新檔案:
import { useState } from 'react';
const [ message, setMessage ] = useState("idle");
const [ loading, setLoading ] = useState(false);
export const catchError = (e:any, message:string) => {
//throw new Error(e)
setMessage(message);
setLoading(false);
console.error(e);
};
但是,當我呈現這個時,我收到以下編譯錯誤:
編譯失敗
src/hooks/catchError.tsx 第 3:33 行:無法在頂層呼叫 React Hook“useState”。React Hooks 必須在 React 函陣列件或自定義 React Hook 函式中呼叫 react-hooks/rules-of-hooks 第 4:33 行:不能在頂層呼叫 React Hook “useState”。React Hooks 必須在 React 函陣列件或自定義 React Hook 函式中呼叫 react-hooks/rules-of-hooks
搜索關鍵字以了解有關每個錯誤的更多資訊。
這對我來說是新領域,所以我一直在努力尋找解決方案,并希望您能提供任何意見來解決問題。
謝謝。
(Ps 我對反應/打字稿還很陌生,所以如果我的術語有誤,我很抱歉。我歡迎在這方面進行任何更正。)
uj5u.com熱心網友回復:
如果您想重用鉤子邏輯(如 useState),您可以撰寫自己的自定義鉤子。
我相信像這樣的東西可以作業,盡管我不完全確定在沒有更多背景關系的情況下如何使用它。
import { useState } from 'react';
function useCatchError() {
const [ message, setMessage ] = useState("idle");
const [ loading, setLoading ] = useState(false);
const catchError = (e:any, message:string) => {
//throw new Error(e)
setMessage(message);
setLoading(false);
console.error(e);
};
return { catchError, message, loading };
}
并像這樣使用
export function Foo() {
const {catchError, message, loading} = useCatchError();
try {
bar();
} catch (e) {
catchError(e, e.message);
}
return (
<div>
{message ? `Error: ${message}` : loading ? "Loading" : "Foo"}
</div>
);
}
更多關于 React 檔案中的自定義鉤子:https : //reactjs.org/docs/hooks-custom.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374209.html
