繁体   English   中英

setInterval 使用 nextjs 和钩子

[英]setInterval using nextjs and hooks

我正在准备使用 nextjs 和钩子实现加载。 我必须每 3 分钟检查一次新信息,当附加信息时,我想使用加载。 我创建了一个 setLoading,它从 false 开始,在 setIntervar 内部传递到 true,但我不知道为什么不工作.. 为什么? 谢谢!

这是我的代码:

import React, { useState, useEffect } from "react";
import Context from "../../config/Context";
import { checkNewData } from "../../helper/index";

function Home() {

  const [contentLoading, setLoading] = useState(false);
  const data = context.events[0];

  useEffect(() => {
    setInterval(() => {
      if (data.live == false) {
        setLoading(true);
        checkNewData();
      }
      setLoading(false)
    }, 10000);

  return (
    <React.Fragment>
      {contentLoading ? <p>loading</p> : <p>no loading</p>
    </React.Fragment>
  );
}

export default Home;

好的,所以在这里你有工作间隔

(每 3 秒调用一次 api,并计算它工作的次数(不需要仅供参考)

在负责Api 调用的函数中,您应该打开加载器 - 然后每3 秒再次调用一次数据


const Home = (props) => {

        const [loading, setLoading] = useState(false);
        const [check, setCheck] = useState(0)

        const callApi = () => {
            Here you should call your api + set loader
            if fetching(setLoading(true))
            if fetched(setLoading(false))
        }

        useEffect(() => {
            const id = setInterval(() => {
                callApi()
                setCheck(check + 1)
            }, 3000);
            return () => clearInterval(id);
        }, [check])

        return (
            <React.Fragment>
                {loading ? <p>Loading</p> : <p>No Loading</p>}
                <p>Times check execute {check}</p>
            </React.Fragment>
        );
    }

现在更好的方法是使用像SWR这样的插件。 它将无缝地处理数据获取甚至加载状态。 在此处查看文档: https ://swr.vercel.app

暂无
暂无

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

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