我在理解在函式中使用/呼叫我的自定義鉤子的最佳方法時遇到了重大問題。在我重新發送的代碼中,我試圖在我的 app.js 中呼叫自定義提取鉤子
我想將以下屬性(姓名和年齡)發送到我的服務器以處理那里的資料庫存盤,因此我打算在用戶填寫姓名和年齡后單擊按鈕時執行此操作。下面的代碼
應用程式.js
const [name, setName] = useState('Owen');
const [age, setAge] = useState(22);
const handleClick = () => {
//if statement to check that name and age where provided
const {data,error} = useFetchPost('url',{name:name,age:age});
}
使用FetchPost.js
const useFetchPost = ({url, val}) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(()=> {
fetch(url,{method:'POST',header: {'Content-Type': 'application/json'},
body:JSON.stringify(val)})
.then(res => return res.json())
.then(data => setData(data))
.catch(err => setError(err))
}, [url, val])
return { data, error }
}
uj5u.com熱心網友回復:
鉤子需要在組件渲染時呼叫,而不是在點擊發生時。但是你可以讓你的鉤子回傳一個函式,然后在handleClick中呼叫那個函式。例如:
const useFetchPost = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const doFetch = useCallback((url, val) => {
fetch(url, {
method: "POST",
header: { "Content-Type": "application/json" },
body: JSON.stringify(val),
})
.then((res) => res.json())
.then((data) => setData(data))
.catch((err) => setError(err));
}, []);
return { data, error, doFetch };
};
// used like:
const App = () => {
const { data, error, doFetch } = useFetchPost();
const handleClick = () => {
doFetch(url, {
method: "POST",
header: { "Content-Type": "application/json" },
});
};
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/463499.html
標籤:javascript 反应 反应钩子
上一篇:如何通過forEach掛載物件?
