React中的鉤子函數(shù)只能在函數(shù)組件或自定義鉤子中使用
??當(dāng)我們需要將React中鉤子函數(shù)提取到一個公共區(qū)域時,就可以使用鉤子函數(shù)
- 自定義鉤子就是一個普通函數(shù),只是它的名字需要以use開頭
- 將方法體和state變量封裝在鉤子函數(shù)中,鉤子函數(shù)本身暴露于外
- 將組件所需的方法變量和state變量封裝于一個對象中,并將該對象作為鉤子函數(shù)的返回值返回,于是就成了鉤子函數(shù)
自定義鉤子函數(shù)請求數(shù)據(jù):
import { useState,useCallback } from 'react'
const useFetch = (dataObj,callback) => {
/**
* dataObj{ url,method }
*/
/**
* 存儲返回數(shù)據(jù)
*/
const [data, setData] = useState([])
/**
* 設(shè)置數(shù)據(jù)的加載狀態(tài)
*/
const [loading, setLoading] = useState(false)
/**
* 創(chuàng)建一個state來記錄異常時拋出的錯誤信息
*/
const [error, setError] = useState(null)
// 請求數(shù)據(jù)函數(shù)
const callFetch = useCallback(async (person) => {
try {
setLoading(true)
setError(null)
//請求數(shù)據(jù)響應(yīng)
const res = await fetch(`http://localhost:1337/api/students/${dataObj.url}`, {
method:dataObj.method.toLowerCase() || 'get',
headers:{'Content-type':'application/json'},
body:(dataObj.method.toLowerCase()==='get')?null:JSON.stringify({data:person})
})
//請求成功時執(zhí)行
if (res.ok) {
const fetchData = await res.json()
setData(fetchData.data)
callback && callback()
} else {
console.log(456);
throw new Error('請求數(shù)據(jù)失敗')
}
} catch (e) {
setError(e)
} finally {
setLoading(false)
}
},[])
// 返回callFetch函數(shù)以及相關(guān)state
return {
loading,
data,
error,
callFetch
}
}
export default useFetch;