React中的钩子函数只能在函数组件或自定义钩子中使用
当我们需要将React中钩子函数提取到一个公共区域时,就可以使用钩子函数
- 自定义钩子就是一个普通函数,只是它的名字需要以use开头
- 将方法体和state变量封装在钩子函数中,钩子函数本身暴露于外
- 将组件所需的方法变量和state变量封装于一个对象中,并将该对象作为钩子函数的返回值返回,于是就成了钩子函数
自定义钩子函数请求数据:
import { useState,useCallback } from 'react'
const useFetch = (dataObj,callback) => {
/**
* dataObj{ url,method }
*/
/**
* 存储返回数据
*/
const [data, setData] = useState([])
/**
* 设置数据的加载状态
*/
const [loading, setLoading] = useState(false)
/**
* 创建一个state来记录异常时抛出的错误信息
*/
const [error, setError] = useState(null)
// 请求数据函数
const callFetch = useCallback(async (person) => {
try {
setLoading(true)
setError(null)
//请求数据响应
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})
})
//请求成功时执行
if (res.ok) {
const fetchData = await res.json()
setData(fetchData.data)
callback && callback()
} else {
console.log(456);
throw new Error('请求数据失败')
}
} catch (e) {
setError(e)
} finally {
setLoading(false)
}
},[])
// 返回callFetch函数以及相关state
return {
loading,
data,
error,
callFetch
}
}
export default useFetch;