react 中关于生命周期请教

2023-03-31 11:04:22 +08:00
 e2e
///这边 我一在页面加载的时候就通过监听 redux 里面正在播放的歌曲, 每次歌曲发生变化的时候 也会获取他 //的 id 然后重新修改页面, 但是每次切换歌曲的时候他总是不能及时切换, 比如你正在放歌曲 A 现在要换 B 那么他会从你点击时候起放 1 秒左右的 A 在切换到 B

const currentMusic = useSelector(state => state.audioData.currentMusic) as ListItem; //获取正在播放的歌曲
useEffect(() => {
    dispatch(isPlaying(false))
    setCurrentMusic(currenrMusicState)
    const id = currentMusic.id;
    const songsid = currentMusic.id;
    const params = {
      id,
      cookie
    };
    if(id) {
      dispatch(musicDetailPage({ songsid })); //获取歌曲信息
      dispatch(songsState(id)) //获取音乐状态
      setMusicFalg(true)
      if(cookie){
        dispatch(recommedUserListDataState(params));
      }
      //讲正在播放的歌曲添加到历史播放
      const copyHistoryList = [...historyList];
      const index = copyHistoryList.findIndex(item => item.id === id);
      if(index !== -1) {
        const song = { ...copyHistoryList[index] };
        copyHistoryList.splice(index, 1);
        copyHistoryList.unshift(song);
      } else {
        const copyList = JSON.parse(JSON.stringify(currentMusic));
        copyHistoryList.unshift(copyList);
      }
      dispatch(songHistoryListData(copyHistoryList));
    }
    console.log(currentMusic);
  }, [currentMusic]);
  const historyList = useSelector(state => state.audioData.songHistoryList) || []
  const handleEnded = () => {
    if(currentSongsIndex < historyList.length) {
      setCurrentSongsIndex(currentSongsIndex + 1)
      dispatch(currentMusicData(historyList[currentSongsIndex]))
      if(audioRef.current) {
        audioRef.current.play()
      }
    }else {
      setCurrentSongsIndex(0)
      dispatch(currentMusicData(historyList[currentSongsIndex]));
      if(audioRef.current) {
        audioRef.current.play()
      }
    }
  };

还有一个就是下面这段代码 我在监听到歌曲播放完毕以后想让他自动切换到下一首,但是他在播放完了之后会一直停在这个这一首上面,我重新刷新进入页面以后他才会吗正确的渲染historyList里面的下一首歌曲

256 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/928704

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX