import React, { useState, useEffect } from 'react';
导入我的钩子
function useFetch(url, defaultResponse) {
const [data, setData] = useState(defaultResponse);
async function getDataFromAPI(url) {
try {
const res = await fetch(url);
const data = await res.json();
setData({
isLoading: false,
data
})
} catch (e) {
console.log(e);
}
}
useEffect(() => {
getDataFromAPI(url);
}, [url])
return data;
}
创建了一个自定义钩子
export default function YouTubeData() {
const channelID = "UCXgGY0wkgOzynnHvSEVmE3A";
const APIKEY = "my-working-key";
const results = 4
const apiEndpoint = `https://www.googleapis.com/youtube/v3/search?key=${APIKEY}&channelId=${channelID}&part=snippet,id&order=date&&maxResults=${results}`
const userFetchResponse = useFetch(apiEndpoint, { isLoading: true, data: null });
if (!userFetchResponse.data || userFetchResponse.isLoading) {
return 'Loading...'
}
当我控制台日志userFetchResponse.data.items时,我得到一个带有属性的对象数组
const {videoId} = (userFetchResponse.data.items.map(obj => "http://www.youtube.com/embed/" + obj.id.videoId));
return (
<div>
{
videoId.map((link, i) => {
var frame =
<div key={i} className='youtube'>
<iframe
title={i}
width="560"
height="315"
src={link}
frameBorder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen>
</iframe>
</div>
return frame
})
}
{this.frame}
</div>
)
}
我正在尝试创建一个变量 videoID 来保存 jsx src 所需的 4 个 URL 数组,但我不断收到未定义的错误,有人可以帮忙吗?
const {videoId} = (userFetchResponse.data.items.map(obj => "http://www.youtube.com/embed/" + obj.id.videoId));
右手边是使用map
的数组,左边也必须是数组。
const videoId = arr[0]
// or
const [videoId] = arr
但不是{videoId
,因为这会假设你在右手边有一个物体。
当你这样做时
const {someVar} = something
与
const someVar = something.someVar
在您的情况下,您只想将数组存储到变量中,因此您只需要
const videoIds = userFetchResponse.data.items.map(obj => "http://www.youtube.com/embed/" + obj.id.videoId);