实现一个网络请求,需要考虑 loading,竞态处理,时序控制,组件卸载等等方面
封装异步请求
import React, { useState, useEffect } form 'react';
function useAsync() {
const [loading, setLoading] = useState(false);
const count = useRef(0);
const [user, setUser] = useState('');
useEffect(() => {init()}, []);
async function init() {
const {current} = count;
if(current !== count.current) return;
setLoading(true);
const res = await $getUserById(userId);
if(res.code !== 0) return;
setLoading(false);
setUser(res.data);
return () => {
count.current += 1;
}
}
}
export default useAsync;
轮询发送请求
请求时序控制
组件卸载放弃网络请求