![](/img/trans.png)
[英]What is the right way to assign element of an array to state using React hooks?
[英]Using Custom hooks in React the right way
我在理解在 function 中使用/調用我的自定義掛鈎的最佳方法時遇到了重大問題。在我重新發送的代碼中,我試圖在我的 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 }
}
鈎子需要在組件渲染時調用,而不是在點擊發生時調用。 但是您可以讓鈎子返回function,然后在 handleClick 中調用該 function。 例如:
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" },
});
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.