【问题标题】:useEffect dependancy arrayuseEffect 依赖数组
【发布时间】:2022-01-11 01:03:55
【问题描述】:

我正在使用 customHook 从 API 获取数据。

const useFetch = () => {
   const dispatch = useDispatch();
   return async (callback, ...props) => {
      try {
         return await callback(...props);
      } catch (error) {
         const { msg } = error.response?.data || "Something went wrong";
         dispatch(showModal(msg));
         setTimeout(() => dispatch(hideModal()), 3000);
      }
   };
};

并在 useEffect 中使用它

const customFetch = useFetch();
useEffect(() => {
      (async () => {
         const data = await customFetch(fetchUsers, token);
         if (data) setUsers(data.user);
      })();
   }, [token]);

但是 eslint 抱怨缺少 customFetch 依赖项。如果我添加它,它将以无限循环结束。我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs use-effect


    【解决方案1】:

    所以你只需要在这里useCallback 让回调你返回稳定:

    const useFetch = () => {
       const dispatch = useDispatch();
       const fetcher = useCallback(async (callback, ...props) => {
          try {
             return await callback(...props);
          } catch (error) {
             const { msg } = error.response?.data || "Something went wrong";
             dispatch(showModal(msg));
             setTimeout(() => dispatch(hideModal()), 3000);
          }
       }, [dispatch]);
       return fetcher;
    };
    

    useMemouseCallback 在这种情况下特别有用,当您需要引用相同的东西,而创建/返回字面上会在每次运行时提供新实例(函数、数组、对象)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-09
      • 2021-10-11
      • 2021-09-29
      • 2020-04-29
      • 1970-01-01
      • 2022-06-12
      • 2021-07-25
      • 2020-04-15
      相关资源
      最近更新 更多