Fetch和setInterval反应钩子问题

时间:2020-09-30 19:29:02

标签: reactjs react-hooks fetch setinterval

我最近在React中使用了钩子来从服务器获取数据,但是我面临着钩子的问题。该代码似乎是正确的,但看起来好像不是第一次调用useEffect,而是在setInterval之后3秒调用它。在出现空白表之前,我有3秒钟的时间。我想直接显示数据并在3秒后调用它。

使用它的正确方法是什么?

const [datas, setDatas] = useState([] as any);

  useEffect(() => {
    const id = setInterval(() => {
        const fetchData = async () => {
          try {
            const res = await fetch(URL);
            const json = await res.json();
            setDatas(jsonData(json));
          } catch (error) {
            console.log(error);
          }
        };
        fetchData();
    }, TIME)

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

2 个答案:

答案 0 :(得分:2)

您首先需要在间隔之外调用一次fetchData。在间隔之外定义fetchData

useEffect(() => {
  // (1) define within effect callback scope
  const fetchData = async () => {
    try {
      const res = await fetch(URL);
      const json = await res.json();
      setDatas(jsonData(json));
    } catch (error) {
      console.log(error);
    }
  };
    
  const id = setInterval(() => {
    fetchData(); // <-- (3) invoke in interval callback
  }, TIME);

  fetchData(); // <-- (2) invoke on mount

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

答案 1 :(得分:0)

使用React Hooks:

  const [seconds, setSeconds] = useState(0)

  const interval = useRef(null)

  useEffect(() => { if (seconds === 60) stopCounter() }, [seconds])

  const startCounter = () => interval.current = setInterval(() => {
    setSeconds(prevState => prevState + 1)
  }, 1000)

  const stopCounter = () => clearInterval(interval.current)