如何连续向API发出GET请求?

我正在向我的数据库发出 GET 请求,数据正在进入并显示,但是当数据在我的数据库上更新时,它不会在使用该数据的组件上更新。


编辑 根据我需要不断发出 GET 请求的评论,所以我更新了问题。


useEffect() 设置数据状态


// Data for each of the tags

const [tag1, setTag1] = useState();

const [tag2, setTag2] = useState();

const [tag3, setTag3] = useState();


useEffect(() => {

    axios

        .get(URL)

        .then(res => {

            const data = res.data;

            // Passing in the setter method

            setTagDetails(data, setTag1, setTag2, setTag3);

        })

        .catch(error => {

            console.log(error);

        });

}, []);


setTagDetails() 其中传入的数据被分成不同的状态以在组件中使用:



// Splitting the data by each corresponding tag and adding them to their respective state

export const setTagDetails = (data, setTag1, setTag2, setTag3) => {

    const arr1 = [];

    const arr2 = [];

    const arr3 = [];

    try {

        data &&

            data.forEach(d => {

                // Entries into the database which do not have any tag information

                // have a size of 5 and those with all the details have a size of 6

                const sizeOfObject = Object.keys(d).length;

                // Only need database items with all the details

                if (sizeOfObject > 5) {

                    // Split the data for the tags into their respective name

                    const name = d["tags"]["L"][0]["M"]["name"]["S"];

                    // Will be used to set individual datasets for each tag

                    if (name === "Tag1") {

                        cleanTag(d, arr1);

                    }

                    if (name === "Tag2") {

                        cleanTag(d, arr2);

                    }

                    if (name === "Tag3") {

                        cleanTag(d, arr3);

                    }

                }

            });

        setTag1(arr1);

        setTag2(arr2);

        setTag3(arr3);

    } catch (err) {

        console.log(err);

    }

};


斯蒂芬大帝
浏览 104回答 1
1回答

qq_花开花谢_0

当你想每隔 x 时间执行一个函数时,我们使用setInterval 方法。它将每隔 x 毫秒调用传入的函数(作为第一个参数)(其中 x 是第二个参数,在下面的示例中为 1000 毫秒或 1 秒)。useEffect(() => {const interval = setInterval(() => {   axios    .get(URL)    .then(res => {        const data = res.data;        // Passing in the setter method        setTagDetails(data, setTag1, setTag2, setTag3);    })    .catch(error => {        console.log(error);    });  }, 1000);  return () => clearInterval(interval);}, []);请注意,在移动网络速度较慢或 ISP 政策带宽受限的情况下,最好注意用户的互联网连接。将请求如此紧密地运行在一起也有危险,以至于我们引入了竞争条件。最后,您必须清除间隔,否则会严重影响应用程序的性能。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript