今天分享一个get API的自定义hook做法,这个hook可以依据不同需求去做调整,我只是提供了做法和概念,当然也可以整合不同的方法,但是要考虑每支api的资料回传及带入参数的作法,如果有高度相同的话就可以用此方法来整合,但如果差异性太大的话还是建议思考一下,是否用另外的custom hook来区分不同做法的模组,不然如果设计出来的hook仍然需要带入过多的参数的话是否失去原本简化的目的。
一般的作法:
// in function component before return const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { setLoading(true) axios.get(api_url) .then((res)=>{ setData(res.data) }) .catch(err => { setError(err); }) .finally(() => { setLoading(false); }) },[])
那我们来看看custom hook的作法,这次我会用axios的做法来处理http的request,如果习惯使用fetch的朋友也可以将该段落换成fetch的作法。
// custom hookimport { useEffect, useState } from "react"import axios from "axios"// 可以以此类推做出不同方法的拿取hooksconst useFetch = (url) => { const [data, setData] = useState(null); // 方便你切换loading的动画图示 const [loading, setLoading] = useState(false); // 错误显示 const [error, setError] = useState(null); // 带入url的参数进来,同理也可将其他参数透过此方法来整合 useEffect(() => { setLoading(true); axios.get(url) .then(res => { setData(res.data); }) .catch(err => { setError(err); }) .finally(() => { setLoading(false); }) }, [url]) // 这里重新拿取的部分就非必要性了,但也提供大家参考 const refetch = () => { setLoading(true); axios.get(url) .then(res => { setData(res.data); }) .catch(err => { setError(err); }) .finally(() => { setLoading(false); }) } // 回传的部分就是将状态、资料、错误和重新拿取的function打包成物件的形式。 return { data, loading, error, refetch };}export default useFetch
再回到原本的component中修改并引入刚刚写好的useFetch()
// in function component before return const { data, loading, error, refetch } = useFetch(api_url);
这样的作法在引入多个不同的api的时候,保持了各自独立又简化了原本的code,当然也可以做成Post, put, delet的不同方法来扩充成不同的hook,就是看需求来做整合了。
那么,今天的分享就到这边,希望有帮助到大家。