Javascript 以编程方式调用钩子

Javascript 以编程方式调用钩子,javascript,reactjs,react-hooks,polling,Javascript,Reactjs,React Hooks,Polling,请参阅上面的url,以获得我的代码的一个非常简化的版本 我希望能够在一定的时间间隔内使用钩子从API中重新提取数据(基本上是轮询端点以获取数据) 我想要的是能够调用类似于refetch(正如我在代码中作为注释显示的那样)的东西,它本质上只是再次调用fetchData,并相应地用响应更新状态 最好的办法是什么?我能想到的唯一方法是在钩子中添加一个checker变量,该变量将是某种uuid(Math.random()可能),返回setChecker作为refetch的内容,并将checker作为第二

请参阅上面的url,以获得我的代码的一个非常简化的版本

我希望能够在一定的时间间隔内使用钩子从API中重新提取数据(基本上是轮询端点以获取数据)

我想要的是能够调用类似于
refetch
(正如我在代码中作为注释显示的那样)的东西,它本质上只是再次调用
fetchData
,并相应地用响应更新状态

最好的办法是什么?我能想到的唯一方法是在钩子中添加一个
checker
变量,该变量将是某种uuid(
Math.random()
可能),返回
setChecker
作为
refetch
的内容,并将
checker
作为第二个useffect参数添加到数组中,以控制重新排序。因此,无论何时调用
refetch
,它都会调用
setChecker
,更新随机数(
checker
),然后该函数再次运行


显然,这听起来很“骇客”,一定有更好的方法来做这件事-有什么想法吗?

如果你想持续进行投票,我想你可以像这样将
setInterval()
移动到钩子中:

function useFetch() {
  const [data, setDataState] = useState(null);
  const [loading, setLoadingState] = useState(true);
  useEffect(() => {
    function fetchData() {
      setLoadingState(true);
      fetch(url)
        .then(j => j.json())
        .then(data => {
          setDataState(data);
          setLoadingState(false);
        });
    }

    const interval = setInterval(() => {
      fetchData();
    }, 5000);

    fetchData();

    return () => clearInterval(interval);
  }, []);

  return [
    {
      data,
      loading
    }
  ];
}
记住包括
return()=>clearInterval(interval)因此钩子被正确清理。

从“React”导入React,{useffect,useState,useCallback};
import React, { useEffect, useState, useCallback } from "react";
import ReactDOM from "react-dom";

const url = "https://api.etilbudsavis.dk/v2/dealerfront?country_id=DK";

function useFetch() {
  const [data, setDataState] = useState(null);
  const [loading, setLoadingState] = useState(true);
  const refetch = useCallback(() => {
    function fetchData() {
      console.log("fetch");
      setLoadingState(true);
      fetch(url)
        .then(j => j.json())
        .then(data => {
          setDataState(data);
          setLoadingState(false);
        });
    }
    fetchData();
  }, []);

  return [
    {
      data,
      loading
    },
    refetch
    // fetchData <- somehow return ability to call fetchData function...
  ];
}

function App() {
  const [
    { data, loading },
    refetch
    // refetch
  ] = useFetch();

  useEffect(() => {
    const id = setInterval(() => {
      // Use the refetch here...
      refetch();
    }, 5000);
    return () => {
      clearInterval(id);
    };
  }, [refetch]);

  if (loading) return <h1>Loading</h1>;
  return (
    <>
      <button onClick={refetch}>Refetch</button>
      <code style={{ display: "block" }}>
        <pre>{JSON.stringify(data[0], null, 2)}</pre>
      </code>
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
从“react dom”导入react dom; 常量url=”https://api.etilbudsavis.dk/v2/dealerfront?country_id=DK"; 函数useFetch(){ const[data,setDataState]=useState(null); 常量[loading,setLoadingState]=useState(true); const refetch=useCallback(()=>{ 函数fetchData(){ 控制台日志(“获取”); 设置加载状态(真); 获取(url) .然后(j=>j.json()) 。然后(数据=>{ setDataState(数据); 设置加载状态(假); }); } fetchData(); }, []); 返回[ { 数据, 加载 }, 重新蚀刻 //获取数据{ 常量id=setInterval(()=>{ //使用此处的重新蚀刻。。。 重新蚀刻(); }, 5000); return()=>{ 清除间隔(id); }; },[refetch]); 如果(装载)返回装载; 返回( 重新蚀刻 {JSON.stringify(数据[0],null,2)}
); } const rootElement=document.getElementById(“根”); render(,rootElement);
也许下面的方法可以工作,它需要一些调整才能使用fetch,但您仍然可以在其他地方正常调用它

export default function App() {
  const [entities, setEntities] = useState();
  const [loading, setLoadingState] = useState(true);

  const getEntities = () => {
    setLoadingState(true);

    //Changet the URL with your own
    fetch("http://google.com", {
      method: "GET",
    })
      .then((data) => data.json())
      .then((resp) => {
        setEntities(resp);
        setLoadingState(false);
      });
  };

  useEffect(() => {
    const interval = setInterval(() => {
      getEntities();
    }, 5000);

    return () => clearInterval(interval);
  }, []);
}


问题的简单答案:

此外,您还可以使用
export default function App() {
  const [entities, setEntities] = useState();
  const [loading, setLoadingState] = useState(true);

  const getEntities = () => {
    setLoadingState(true);

    //Changet the URL with your own
    fetch("http://google.com", {
      method: "GET",
    })
      .then((data) => data.json())
      .then((resp) => {
        setEntities(resp);
        setLoadingState(false);
      });
  };

  useEffect(() => {
    const interval = setInterval(() => {
      getEntities();
    }, 5000);

    return () => clearInterval(interval);
  }, []);
}