简体   繁体   English

setInterval 使用 nextjs 和钩子

[英]setInterval using nextjs and hooks

I' m traying to implement a loading using nextjs and hooks.我正在准备使用 nextjs 和钩子实现加载。 I have to do a fetch to check new info every 3 minutes and when thats appends I want to use a loading.我必须每 3 分钟检查一次新信息,当附加信息时,我想使用加载。 I create a setLoading and it starts at false and inside a setIntervar pass to true, but I dont 'know why dosen 't work.. why?我创建了一个 setLoading,它从 false 开始,在 setIntervar 内部传递到 true,但我不知道为什么不工作.. 为什么? Thanks!谢谢!

here is my code:这是我的代码:

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;

Ok, so here You have working interval好的,所以在这里你有工作间隔

(Every 3 sec calling api, and counts how many times it works(not needed just FYI) (每 3 秒调用一次 api,并计算它工作的次数(不需要仅供参考)

In the function responsible for Api call you should turn on the loader - then every 3 seconds the data is called again在负责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>
        );
    }

A better way to do this now will be to use a plugin like SWR .现在更好的方法是使用像SWR这样的插件。 It will handle the data fetch and even the loading state seamlessly.它将无缝地处理数据获取甚至加载状态。 Check the documentation here: https://swr.vercel.app在此处查看文档: https ://swr.vercel.app

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

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