实现一个网络请求,需要考虑 loading,竞态处理,时序控制,组件卸载等等方面

封装异步请求

  1. import React, { useState, useEffect } form 'react';
  2. function useAsync() {
  3. const [loading, setLoading] = useState(false);
  4. const count = useRef(0);
  5. const [user, setUser] = useState('');
  6. useEffect(() => {init()}, []);
  7. async function init() {
  8. const {current} = count;
  9. if(current !== count.current) return;
  10. setLoading(true);
  11. const res = await $getUserById(userId);
  12. if(res.code !== 0) return;
  13. setLoading(false);
  14. setUser(res.data);
  15. return () => {
  16. count.current += 1;
  17. }
  18. }
  19. }
  20. export default useAsync;

轮询发送请求

请求时序控制

组件卸载放弃网络请求