我有一個按鈕,onClick在那個按鈕中,我想POST與一些資料進行通話,用戶填寫了輸入欄位,存盤在狀態中,然后將用戶重定向到另一個頁面。
我當前的代碼如下所示,但出現錯誤:
React Hook "usePost" 在函式 "onAccept" 中被呼叫,該函式既不是 React 函陣列件也不是自定義 React Hook 函式
而且代碼不起作用。我創建了自己的POST呼叫掛鉤。
有什么方法可以使所需的功能起作用?
我所追求的是能夠進行 POST 呼叫和重定向。
簡化示例:
// my function
const onAccept = () => {
const { data, loading, error } = usePost(
"MY_URL",
{ DATA: MY_DATA }
);
if (data && !error) {
navigate(`/`);
}
};
// return
<button onClick={() => onAccept()}
uj5u.com熱心網友回復:
是的,您在函式usePost內部呼叫鉤子。onAccept你應該遵循react hook rule。
要解決您的問題,您可以這樣做:
您的自定義掛鉤檔案:
export const usePost = () => {
const [status, setStatus] = useState()
const handlePost = useCallback(async (url, data) => {
// your api request logic in here, bellow only show example
try {
const {data, status} = await apiCall(url, data)
if (data && status === 200) navigate(`/`)
} catch (error) {
console.log(error)
}
}, [])
return { handlePost }
// to return status to component, you can use bellow.
// return { status, handlePost }
}
然后你的組件:
const YourComponent: React.FC = () => {
const { handlePost } = usePost()
// To get status: const { status, handlePost } = usePost()
// your other hooks in here
// Check status
useEffect(() => {
if (status === 200) {
// whatever you want to do
}
}, [status])
return (
<>
// Your component UI here
...
<button onClick={() => handlePost(url, data)}>
</>
)
}
usePost您應該在組件的頂層呼叫自定義鉤子(例如:) ,而不是像在代碼(onAccept函式體)中那樣嵌套函式體。
uj5u.com熱心網友回復:
我可以建議您執行以下操作。
首先,您應該創建將從usePost hook.
例子。
export const usePost = () => {
const [loading, setLoading] = useState(false)
const [data, setData] = useState([])
const fetch = () => {
setStatus(loading)
apiRequest({
url: 'my_url',
method: 'GET',
}).then(response => {
setStatus(false)
setData(response.data.data)
}).catch(e => {
setStatus(false)
})
}
return {
status,
data,
fetch
}
畢竟,你可以在你的組件中呼叫這個鉤子。它將回傳fetch函式。你應該在里面呼叫 fetch onAccept。
例子。
const { data, loading, fetch } = usePost()
const onAccept = () => {
fetch()
}
// return
<button onClick={() => onAccept()}
PS。如果需要,您也可以從usePost hook, 回傳錯誤。
uj5u.com熱心網友回復:
首先,從 React Function 呼叫你的鉤子。閱讀檔案:https ://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions 。
其次,您的鉤子中應該有某種load方法,例如: ,以便在點擊時發出 POST 請求。usePostconst { load } = usePost(...)
所以你的處理程式看起來像:
const onAccept = () => {
load();
// the following block move somewhere before you render the component or better use useEffect hook for that
// if (data && !error) {
// navigate(`/`);
// }
};
我希望這將有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527638.html
上一篇:在Kivy中每秒顯示一個亂數
