简体   繁体   English

React 应用程序使用自定义 useRequest 钩子不断重新渲染

[英]React app keeps re-rendering with custom useRequest hook

In my application I created a custom hook to make API requests:在我的应用程序中,我创建了一个自定义挂钩来发出 API 请求:

const useRequest = (promise) => {
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState({});
  useEffect(() => {
    let ignore = false;
    const fetchProduct = async () => {
      try {
        setLoading(true);
        const response = await promise;
        if (!ignore) setData(response);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };
    fetchProduct();
    return () => {
      ignore = true;
    };
  }, [promise]);
  return { data, loading, error };
};
export default useRequest;

And in my component I use it as:在我的组件中,我将其用作:

const { data, loading, error } = useRequest(api.user.getAll());

where api.user.getAll() is a function that returns a promise.其中api.user.getAll()是返回 promise 的 function。 The component renders and it displays the data however it keeps re-rendering and refetching data multiple times.该组件渲染并显示数据,但它会多次重新渲染和重新获取数据。 What might be the problem that is causing this?导致这种情况的问题可能是什么? Are there multiple instances of promises being created that trigger the hook to run again?是否有多个正在创建的 Promise 实例触发钩子再次运行?

where api.user.getAll() is a function that returns a promise.其中api.user.getAll()是返回 promise 的 function。 [...] Are there multiple instances of promises being created that trigger the hook to run again? [...] 是否有多个正在创建的 Promise 实例触发钩子再次运行?

Yes, every time your component gets rendered, it calls api.user.getAll() .是的,每次渲染您的组件时,它都会调用api.user.getAll() Since new Promise (or an async function) will always return a fresh Promise object (and hook deps use strict equality for comparison), the effect is re-run.由于new Promise (或async函数)将始终返回新的 Promise object (并且钩子部门使用严格相等进行比较),因此重新运行效果。

My go-to hammer for requests like this these days is swr ;这些天,我对此类请求的首选锤子是swr maybe look into it?也许调查一下?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM