如何在没有 useEffect 或 setState 函数的情况下重新触发挂钩?

How to re-trigger hook without useEffect or a setState function?

我正在使用自定义挂钩,该挂钩将 URL 作为参数并 returns 获取数据及其加载状态。因此,与大多数挂钩不同,我没有在需要时设置新状态的功能,这在项目的这一点上导致了各种问题,因为我恰好需要一种方法来在每次收到自定义挂钩时重新触发它新道具值。

问题是,正如预期的那样,组件的状态是在组件首次渲染时设置的,但当它收到新的道具时,它不会 re-render/re-trigger。

这是自定义挂钩的样子:

//useFetch.js

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();
    setData(JSON.parse(JSON.stringify(json)));
    setLoading(false);
  }

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

  return [data, loading];
}

export { useFetch };

这就是我使用这个钩子的方式:

//repos.js

import React from "react";
import { useFetch }  from "./fetchHook";


function Repos(props) {
  const [userRepos, reposLoading] = useFetch(`https://api.github.com/users/${props.users[props.count].login}/repos`);

  return reposLoading ? (
    <div className="App">
      stuff to render if it's still loading
    </div>
  ) : (
    <div
     stuff to render if it's loaded
    </div>
  );
}

url 添加到 useFetch hook 的依赖项数组中,这将确保当 url prop 更改

时效果将重新运行
useEffect(() => {
  console.log("refetching url", url);
  fetchUrl();
}, [url]);