ReactNative&Expo:难于增加/减少,以循环通过数组

问题描述 投票:0回答:1

我正在尝试使用从0开始并根据我是否按next或back递增/递减的索引值在数组中的声音对象之间循环。

这是用于使用Expo // expo-av库进行本地播放的音乐播放器。我将包括所有相关代码。

我在上下文文件中的状态:

const initialState = {
  startMusic: () => null,
  stopMusic: () => null,
  soundObject: null,
  isPlaying: false,
  currentIndex: 0,
}
useState()
const [soundObject, setSoundObject] = useState(initialState.soundObject)
const [isPlaying, setIsPlaying] = useState(initialState.isPlaying)
const [currentIndex, setCurrentIndex] = useState(initialState.currentIndex)

开始音乐功能

const startMusic = async () => {
    try {
      const songToPlay = songs[currentIndex].song
      const source = songs[currentIndex].path

      await songToPlay.loadAsync(source)
      await songToPlay.playAsync()
      setSoundObject(songToPlay)
      setIsPlaying(true)
      return new Promise(resolve => {      // I made this promise when I was setting a loop to play through music.  May not need this anymore
        songToPlay.setOnPlaybackStatusUpdate(playbackStatus => {
          if (playbackStatus.didJustFinish) {
            console.log("Song finished")
            resolve()
          }
        })
      })
    } catch (error) {
      console.log(`Error: ${error}`)
      return
    }
  }

最后,应该在歌曲之间循环的处理函数:

const handlePreviousTrack = async () => {
    if (soundObject) {
      await soundObject.stopAsync()
      await soundObject.unloadAsync()
      // setSoundObject(null)
      let newIndex = currentIndex

      newIndex < songs.length - 1 ? newIndex-- : (newIndex = 0)

      setCurrentIndex(newIndex)
      startMusic()

      console.log(currentIndex)
    }
  }

  const handleNextTrack = async () => {
    if (soundObject) {
      await soundObject.stopAsync()
      await soundObject.unloadAsync()
      // setSoundObject(null)
      let newIndex = currentIndex

      newIndex < songs.length - 1 ? newIndex++ : (newIndex = 0)

      setCurrentIndex(newIndex)
      startMusic()

      console.log(currentIndex)
    }
  }

循环浏览下一个/上一个未按顺序进行。有时它会起作用,有时前一首会跳到下一首歌曲,有时会按next播放第一首歌曲。

我是否通过currentIndex错误地操纵了状态?

android reactjs react-native expo mobile-development
1个回答
0
投票

通过快速浏览,我没有发现上面的代码中有任何令人震惊的错误。我的一个建议是将您的startMusic()调用从您的两个handleTrack方法中删除,而只是让它们在执行操作时设置索引状态。

而是添加一个useEffect,它将在每次索引更改时触发,并将您的startMusic()放在该useEffect中。

看起来像这样:

useEffect(() => {
   ... (other logic)
   startMusic()
}, [currentIndex])

这将确保startMusic仅在currentIndex状态已更改后才被调用,而不会被过早调用,如果不这样做,则无论状态如何更改,它都可以更容易地跟踪到它]

© www.soinside.com 2019 - 2024. All rights reserved.