当我的反应组件的状态没有改变时,我如何重新触发自定义钩子?

How can I re-trigger a custom hook inside my react component, when its states have not changed?

我有一个自定义挂钩用于从服务器获取数据。它需要 3 个参数,分别是 pageNumber、pageSize 和 keyword。我知道如果我设置了这些参数中的一个或多个,挂钩会以新状态重新触发。但是在我的组件中,当我创建数据时有一个地方,所以一旦创建它就必须再次获取数据。但是 none 它的参数,如 pageNumber、pageSize 和 keyword 已经更新。我只需要它再次 运行 来获取新数据。我该怎么做,而不改变我的状态? (在下面的代码中,'Adapter' 是一个 Axios 实例)

这是钩子:

const useFetchLists = (
  url = '',
  currentPage = 1,
  selectedPageSize = 10,
  keyword = ''
) => {
  const [items, setItems] = useState([]);
  const [loading, setloading] = useState(false);
  const [totalPage, setTotalPage] = useState(1);
  const [totalItemCount, setTotalItemCount] = useState(0);

  useEffect(() => {
    const fetchListData = async () => {
      try {
        setloading(true);
        await Adapter.get(
          `${url}?pageNumber=${currentPage}&pageSize=${selectedPageSize}&keyword=${keyword}`,
          {}
        ).then((response) => {
          setItems(response.data.items);
          setTotalPage(response.data.totalPages);
          setTotalItemCount(response.data.totalItems);
        });
      } catch (err) {
      } finally {
        setloading(false);
      }
    };
    fetchListData();
  }, [url, currentPage, selectedPageSize, keyword]);

  return [items, loading, totalPage, totalItemCount];
};

export default useFetchLists;

这就是我在页面初始加载时在我的组件中使用它的方式。

 const [currentPage, setCurrentPage] = useState(1);
  const [selectedPageSize, setSelectedPageSize] = useState(10);
  const [keyword, setKeyword] = useState('');
  const [items, loading, totalPage, totalItemCount] = useFetchLists(
    ADD_BRAND_URL,
    currentPage,
    selectedPageSize,
    keyword
  );

我希望能够重新触发挂钩,而不设置其任何状态,因为它们没有改变,但数据已经改变,因此必须重新获取。

我想你可以引入一个 refetch 函数,像这样:

const useFetchLists = (
  url = "",
  currentPage = 1,
  selectedPageSize = 10,
  keyword = ""
) => {
  const [items, setItems] = useState([]);
  const [loading, setloading] = useState(false);
  const [totalPage, setTotalPage] = useState(1);
  const [totalItemCount, setTotalItemCount] = useState(0);

  const fetchListData = useCallback(async () => {
    try {
      setloading(true);
      await Adapter.get(
        `${url}?pageNumber=${currentPage}&pageSize=${selectedPageSize}&keyword=${keyword}`,
        {}
      ).then((response) => {
        setItems(response.data.items);
        setTotalPage(response.data.totalPages);
        setTotalItemCount(response.data.totalItems);
      });
    } catch (err) {
    } finally {
      setloading(false);
    }
  }, [url, currentPage, selectedPageSize, keyword]);

  useEffect(() => {
    fetchListData();
  }, [fetchListData]);

  return {
    data: [items, loading, totalPage, totalItemCount],
    refetch: fetchListData
  };
};

export default useFetchLists;