Loading... ### 自定义useAsync - 统一处理成功和失败以及loading ``` export const useAsync = (asyncFunction, callback, errHandle) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const execute = useCallback( (params, ...args) => { //请求开始时,设置loading为true, 清除已存的数据和错误 setLoading(true); setData(null); setError(null); return asyncFunction(params) .then((response) => { setLoading(false); if (errHandle) { if (!isSuccessNotTip(response)) { errHandle(response, params); return; } } else { if (!isSuccess(response)) { setError(true); return; } } setData(response.data); callback && callback(response, params, ...args); }) .catch((error) => { setLoading(false); setError(true); console.log('失败处理', error); }); }, [asyncFunction], ); return { execute, data, loading, error }; }; ``` ``` export const useOneDevice = (id) => { const [device, setDevice] = useState(); const { execute } = useAsync( useCallback(async (params) => { return devicesApis.getDevices(params); }, []), (resp) => { setDevice(resp.data[0]); }, ); useEffect(() => { if (!id) return; execute({ device_id: id }); }, [execute, id]); return { device }; }; ``` ### 思考 - 自定义hooks在我看来主要用于公共逻辑的抽离封装 ### 参考 https://zhuanlan.zhihu.com/p/109911797 最后修改:2022 年 06 月 20 日 © 允许规范转载 打赏 赞赏作者 赞 0 如果觉得我的文章对你有用,请随意赞赏
8 条评论
文章紧扣主题,观点鲜明,展现出深刻的思考维度。
内容的丰富性和深度让人仿佛置身于知识的海洋,受益匪浅。
你的文章让我学到了很多知识,非常感谢。 https://www.4006400989.com/qyvideo/44091.html
《阿娇正传粤语》韩国剧高清在线免费观看:https://www.jgz518.com/xingkong/110623.html
你的文章总是能给我带来欢乐,谢谢你! http://www.55baobei.com/UpRhpeK2Yr.html
《阿娇正传粤语》韩国剧高清在线免费观看:https://www.jgz518.com/xingkong/110623.html
“传奇私服装备交易真的能换取现实货币吗?”:https://501h.com/heji/2024-10-23/44223.html
《影子舞者》剧情片高清在线免费观看:https://www.jgz518.com/xingkong/73579.html