太多的重新渲染。 React 限制渲染次数以防止无限循环

时间:2021-07-26 13:03:42

标签: reactjs async-await axios

我创建了一个自定义钩子,似乎问题仍然存在我将代码更改为一种使用 fetch 的更简单的方法并且它有效,但似乎我没有抓住无限循环的存在,我能感觉到它有很多错误请指出他们,如果可能的话,任何代码重构都会很棒

import { useState, useCallback } from "react";
import axios from "axios";
const Usehttp = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const sendRequest = useCallback(async (config, option, applyData) => {
    setLoading(true);
    setError(null);
    try {
      const data = await axios.get(config.url, {
        method: config.method ? config.method : "GET",
        body: config.body ? JSON.stringify(config.body) : null,
        headers: config.headers ? config.headers : {},
      });
      if (option === "FETCH" || option === "CREATE") {
        applyData(data);
      } else if (option === "DELETE") {
        applyData("This has been deleted successfully");
      } else if (option === "UPDATE") {
        applyData("This has been updated successfully");
      }
    } catch (error) {
      setError(error.message || "something went wrong");
    }
    setLoading(false);
  }, []);
  sendRequest();
  return {
    loading,
    error,
    sendRequest,
  };
};

export default Usehttp;

1 个答案:

答案 0 :(得分:1)

如果 UseHttp 是自定义钩子 - 您需要重命名为 useHttp,并在组件的顶层使用此钩子;

function Component() {
  const { sendRequest } = useHttp();
}

您还需要为您添加依赖项 useCallback,例如 [applyData, setLoading, setError] 中的 UseHttp