我在 youtube 上使用 javascript mastery API 课程来尝试创建一个 YouTube 克隆,但是在尝试使用 API 获取视频时,我遇到了一些错误,并且 React 应用程序停止了重新渲染。在我输入这一行后发生了错误
{item.id.videoId && <VideoCard video={item}/>}
这是我的视频组件代码
import {Stack, Box} from '@mui/material';
import {ChannelCard, VideoCard} from './';
const Videos = ({videos}) => {
return (
<Stack direction="row" flexWrap="wrap" justifyContent="start" gap={2} >
{videos.map((item, idx) => (
<Box key={idx}>
{item.id.videoId && <VideoCard video={item}/>}
</Box>
))}
</Stack>
)
}
export default Videos
这是错误
Videos.jsx:9 Uncaught TypeError: Cannot read properties of undefined (reading 'videoId')
at Videos.jsx:9:1
at Array.map (<anonymous>)
at Videos (Videos.jsx:7:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1
可能是因为
videoId
在这条路径上:
item.snippet.videoId
响应 - 从“示例响应”选项卡中提取。
{
"kind": "youtube#captionListResponse",
"items": [
{
"kind": "youtube#caption",
"id": "AUieDaZHR-hdtpvJvd_dtt6cuYWaFGFlDocKBzLyQktj",
"snippet": {
"videoId": "M7FIvfx5J10",
"lastUpdated": "2013-11-14T08:09:57.310379Z",
"trackKind": "standard",
"language": "bg",
"name": "",
"audioTrackType": "unknown",
"isCC": false,
"isLarge": false,
"isEasyReader": false,
"isDraft": false,
"isAutoSynced": false,
"status": "serving"
}
},
[...]
]
}
您可能正在学习 JS Mastery 教程。 在 Feed.jsx 中,我在传递“视频”之前忘记删除 []:
<Videos videos={[videos]}/>
并得到了和你一样的错误。
应该是这样的:
<Videos videos={videos}/>