我正在使用youtube api构建一个React应用程序,以使用youtube播放列表填充页面。我正在获取返回的数据,并且能够访问代码段对象中的标题,描述和其他所有内容,缩略图对象除外,该缩略图对象返回未定义并破坏了我的应用程序。
这是我在自定义钩子中的api调用
import { useState, useEffect } from 'react'
import axios from 'axios'
export default function useApiCall() {
const [videos, setVideos] = useState([])
const URL = 'https://www.googleapis.com/youtube/v3/playlistItems'
const id = '---hidden---'
const API_key = '---hidden---'
const params = {
part: "snippet",
playlistId: id,
key: API_key,
maxResults: 30
}
useEffect(() => {
axios
.get(URL, {
params: params
})
.then(res => {
setVideos(res.data.items)
console.log(res)
})
.catch(err => {
console.log(err)
})
},[])
return [videos]
}
这是我的播客组件,它调用自定义钩子
import React from 'react'
import useApiCall from '../../data/useApiCall'
export default function Podcasts() {
const [videos] = useApiCall([])
return (
<div>
{videos && videos.map(vid => {
return (
<div key={vid.id}>
<h3>{vid.snippet.title}</h3>
<img src={vid.snippet.thumbnails.default.url} alt={vid.snippet.title} />
<p>{vid.snippet.description.substring(0, 150)} ...</p>
</div>
)
})}
</div>
)
}
h3和p标签呈现没有问题,但是img破坏了应用程序。
我得到的错误是
The above error occurred in the <Podcasts> component:
in Podcasts (created by Context.Consumer)
in Route (at App.js:17)
in div (at App.js:14)
in App (at src/index.js:11)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:10)
in ParallaxProvider (at src/index.js:9)
TypeError: "vid.snippet.thumbnails is undefined"
Podcasts Podcasts.js:14
Podcasts Podcasts.js:9
React 11
unstable_runWithPriority scheduler.development.js:818
React 5
useApiCall useApiCall.js:23
useApiCall.js:27
TypeError: vid.snippet.thumbnails is undefined
Podcasts.js:14