V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
e2e
V2EX  ›  程序员

react 中关于生命周期请教

  •  
  •   e2e · 2023-03-31 11:04:22 +08:00 · 255 次点击
    这是一个创建于 563 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ///这边 我一在页面加载的时候就通过监听 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里面的下一首歌曲

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2986 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 13:18 · PVG 21:18 · LAX 06:18 · JFK 09:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.