React中自定義鉤子函數(shù)

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;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容