我是一个新的反应,想要创建一个YouTube播放器,像应用组件,存储所有的YouTube播放列表,并显示在我的桌面右侧播放列表(下图),所以我的一个朋友给了我这段代码,但它的一些错误,但它的工作在一开始,但几分钟后,它耗尽了我的google每天的限制和不会返回任何东西,因为你可以看到正确的播放列表div块现在是空的,现在从下面的图像。
请帮我弄清楚为什么它会发送无限的get请求?
*我无法按时获得控制台屏幕截图,但其中包含了很多get请求错误。
代码如下:
import axios from 'axios';
import React from 'react'
import { useState } from "react";
export default function PlayerItem() {
const [data, setData] = useState([]);
const details = []
async function gettingData() {
await axios.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLu0W_9lII9aiL0kysYlfSOUgY5rNlOhUd&key=[myKey]').then(res => {
setData(res.data.items)
});
}
gettingData();
data.forEach(element => {
details.push(element.snippet.title)
});
// console.log(details);
return (
<>
{details.map((title, index) =>
(
<div className="pl-item" key={index}>
<strong>Video {index + 1}</strong> : {title}.
</div>
)
)}
</>
)
}

发布于 2022-07-23 19:10:46
import axios from "axios";
//import useEffect from React
import React, { useEffect, useState } from "react";
//Dont need to import these seperately
//import { useState } from "react";
export default function PlayerItem() {
const [data, setData] = useState([]);
const details = [];
async function gettingData() {
await axios
.get(
"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLu0W_9lII9aiL0kysYlfSOUgY5rNlOhUd&key=[myKey]"
)
.then((res) => {
setData(res.data.items);
});
}
//gettingData() ****
//if we put this into a useEffect then we can stop it re-firing on every render
//at the end there is a an array of states / objects that when they are changed they
//useeffect will refire. If we leave this empty then it only fires on the page loading
useEffect(() => {
gettingData();
}, []);
data.forEach((element) => {
details.push(element.snippet.title);
});
// console.log(details);
return (
<>
{details.map((title, index) => (
<div className="pl-item" key={index}>
<strong>Video {index + 1}</strong> : {title}.
</div>
))}
</>
);
}正如有人已经评论过的那样,实现useEffect,这样它就不会对每个重新呈现(这是由设置状态引起的)触发。在useEffect的末尾有一个空的依赖数组将在页面加载时调用它。
https://stackoverflow.com/questions/73092075
复制相似问题