在 React 中单击/观看视频后,如何从数组中获取'Next video'



在我的React应用程序中,我可以从api查询视频列表(数组(。

单击视频后,如何从数组中获取"下一个视频"?

流程如下:

我用useQuery钩子从GraphQL获得视频:

const { previousData, data: myVideos = previousData, loading, fetchMore } = useQuery<
GqlResponse,
Args
>(GET_VIDEOS, {
errorPolicy: 'all',
notifyOnNetworkStatusChange: true,
});

然后我可以返回一个视频预告片列表:

{myVideos.map((video) => (
<VideoTeaser
key={video.uuid}
title={video.title}
url={video.uuid}
thumbnail={video.thumbnail}
/>
))}

使用另一个GraphQl查询,我基于uuid:查询视频

const { data } = useQuery<GqlResponse, VideoArgs>(GET_VIDEO, {
variables: {
uuid: id,
},
errorPolicy: 'all',
});

我把uuid传给播放器,让它知道要播放哪个视频。

id(上面在GQL变量中(来自一个查询参数:const id = queryParams.videoId as string;

从数组列表中单击视频摘要后,它将uuid发送到url中的查询参数:<Link {...linkProps} to={url}>

然后在另一个div(叠加(中,它在播放器的叠加中播放列表中点击的视频:

<Player
uuid={videoData.uuid}
thumbnail={videoData.image)
}
autoplay
onEnd={onVideoEnd}
/>

因此,在每个覆盖中,当前视频都会播放,在侧边栏中(在现有的视频旁边,总是呈现相同的预告片列表(总是具有相同的数组索引和顺序(。

由于您总是通过其uuid(id(来了解当前播放的视频,因此可以使用Array.findIndex()在视频数组(myVideos(中查找其当前索引。

const id = queryParams.videoId
const currentIndex = myVideos.findIndex(o => o.uuid === id)
const nextIndex = Math.max(currentIndex + 1, myVideos.length - 1) // the index can't go beyond the last item
const nextId = myVideos.of(nextIndex).uuid

你可以对上一项使用相同的想法。

如果您希望下一个是循环的-如果当前是最后一个项目,则跳到第一个项目,使用余数运算符查找nextIndex:

const nextIndex = currentIndex + 1 % myVideos.length 

最新更新