티스토리 뷰

문제

플레이 리스트 index변경 시  상태유지가 되지 않는다

3번 노래 재생 중에 음악을 추가할 경우, 제목순 정렬이라 재생 중인 노래의 인덱스가 5번으로 변경되면 3번 자리에 있는 노래가 재생된다 

삭제할 경우 삭제된 노래가 계속 재생된다


해결과정

뮤직플레이어 컴포넌트에 현재 재생상태를 확인할 수 있는 state를 만들어 플레이어 컴포넌트에 props로 내려줬다

플레이어 컴포넌트는 현재 재생상태를 확인하는 state를 받아 useEffect내부에서 현재 플레이 리스트가 있으면 첫 번째 음악을 현재 재생 중인 음악을 저장하는 state에 담아준다

만약 현재 플리가 없거나 재생 중인 플리를 지우면 state를 비워줘야 하는데 조건문 설정을 잘못하는 바람에 한참 헤맸다

조건을 현재 플리가 있고, 플리목록이 있고, 인덱스가 null이면 상태를 null로 설정해 버림

 이유를 못 찾고 엄한 플리만 전역상태로 전환하고 처리하려 했는데 콘솔로 확인해 보니 조건문에 진입이 안 되는 걸 알았다.

인덱스의 상태까지 조건문에 넣을 필요가 없었다 현재 재생 상태와 플리 목록만 가지고 조건을 넣으면 해결

1. 이런 조건문은 쓰지 말자
2. 조건문에 안 들어가면 그냥 걔를 콘솔에 찍어보자

문제의 조건문
! currentPlaying && currentPlayList.length > 0 && musicIndex === null

 

플레이어 전체 코드

const Player = ({
  currentPlaying,
  setCurrentPlaying,
  isLyrics,
  isRandom,
  currentPlayList,
  musicIndex,
  onPreviousHandler,
  onNextTrackHandler,
  onLyricsToggle,
  onInsertMyPlayListHandler,
  onRandomMusicHandler,
}: PlayerProps) => {
  const [playList, setPlayList] = useState<CurrentPlayListType[]>([])
  // const [currentPlaying, setCurrentPlaying] =
  //   useState<CurrentPlayListType | null>(null)
  // const { currentMusicData } = useCurrentMusicStore()
  // const { currentPlayList, musicIndex } = currentMusicData

  useEffect(() => {
    // if (currentPlayList.length > 0 && musicIndex !== null) {
    //   setPlayList(currentPlayList)
    // }
    console.log('ssssssssssssssssssssssssssssss')
    console.log('currentPlaying,', currentPlaying)
    console.log(' currentPlayList.length === 0 ', currentPlayList.length === 0)
    console.log(' musicIndex ', musicIndex)
    if (!currentPlaying && currentPlayList.length > 0 && musicIndex !== null) {
      // setCurrentPlaying(playList[musicIndex])
      setCurrentPlaying(currentPlayList[musicIndex])
    } else if (currentPlaying && currentPlayList.length === 0) {
      setCurrentPlaying(null)
      console.log('currentPlaying', currentPlaying)
    }
  }, [musicIndex, currentPlayList, currentPlaying])

  // console.log('플리원본', currentPlayList)
  // console.log('플리원본인덱스', currentPlayList[musicIndex])
  // // console.log('플리복사', playList)
  // // console.log('플리+인덱스', playList[musicIndex])
  // console.log('현재 재생곡임', currentPlaying)

  // useEffect(() => {
  //   setPlayList(currentPlayList);
  // }, [currentPlayList]);

  // useEffect(() => {
  //   if (playList.length > 0 && musicIndex !== null) {
  //     setCurrentPlaying(playList[musicIndex])
  //   } else {
  //     setCurrentPlaying(null)
  //   }
  // }, [musicIndex, playList])

  // useEffect(() => {

  // }, [musicIndex, playList])

  const customIcons = {
    play: <MyPlayIcon />,
    pause: <MyPauseIcon />,
    previous: <MyPreviousIcon onPreviousHandler={onPreviousHandler} />,
    next: <MyNextIcon onNextTrackHandler={onNextTrackHandler} />,
    loop: <MyLoopIcon />,
    loopOff: <MyLoopOffIcon />,
    progressJump: <FaForward />,
  }
  const onplayHandler = (arg: any) => {
    setCurrentPlaying(arg)
  }

  // if (!currentPlaying && playList.length > 0) {
  //   setCurrentPlaying(playList[musicIndex])
  // }

  // if (playList.length === 0 && musicIndex === null) {
  //   setCurrentPlaying(null)
  //   console.log('아니 재생중인 노래 삭제했다고', currentPlaying)

  //   currentMusic(currentPlayList, musicIndex)
  // }

  return (
    <div>
      <div className='flex flex-col items-center'>
        <div className='mt-[40px] flex flex-col items-center gap-[8px] p-[0px]'>
          <div className=' text-center text-[20px] font-bold leading-[150%]  tracking-tighter text-white opacity-80'>
            {currentPlaying?.musicTitle}
          </div>

          <div className='text-center text-[18px] leading-[150%] tracking-tighter text-white opacity-50'>
            {currentPlaying?.artist}
          </div>
        </div>
        <div className='relative ml-[44px] mr-[44px] mt-[41px]'>
          <div className='relative h-[300px] w-[300px]'>
            <Image
              src={musicThumbnail}
              alt='Album Circle'
              width={300}
              height={300}
              className='h-[300px] w-[300px]'
            />
          </div>
          <div className='absolute left-[50px] top-[50px] h-[200px] w-[200px] '>
            <Image
              src={currentPlaying ? currentPlaying.thumbnail : musicThumbnail}
              alt='Album Thumbnail'
              width={200}
              height={200}
              className='h-[200px] w-[200px] rounded-full'
            />
          </div>
        </div>
        <div className='mx-auto flex items-center px-[24px]'>
          <div className='flex w-[316px] justify-between'>
            <button onClick={onLyricsToggle} className='h-[48px] w-[48px]'>
              {isLyrics ? (
                <Image src={musicList} alt='Lyrics' width={48} height={48} />
              ) : (
                <Image
                  src={musicLyricsButton}
                  alt='Lyrics'
                  width={48}
                  height={48}
                />
              )}
            </button>
            <button
              type='button'
              onClick={onInsertMyPlayListHandler}
              className='h-[48px] w-[48px]'
            >
              <Image
                src={myPlayListButton}
                alt='Album Circle'
                width={48}
                height={48}
              />
            </button>
          </div>
        </div>
      </div>

      <div className='rhap_controls-section'>
        <AudioPlayer
          src={currentPlaying ? currentPlaying.musicSource : ''}
          volume={0.1}
          loop={false}
          onEnded={onNextTrackHandler}
          showSkipControls={true}
          customIcons={customIcons}
          onPlay={() => {
            onplayHandler(currentPlayList[musicIndex])
          }}
        />
        <Image
          src={isRandom ? musicShuffleOff : musicShuffle}
          alt='Lyrics'
          width={55}
          height={60}
          onClick={onRandomMusicHandler}
          className='shuffleButton'
        />
      </div>
    </div>
  )
}

export default Player
// 함수가 정상적으로 작동하지 않을경우(상태유지 불가 등) 함수 호출부, 사용하는곳부터 뒤져보기!!!!!!!!!!!!!!!!
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함