【问题标题】:Playing audio files with Redux使用 Redux 播放音频文件
【发布时间】:2016-03-31 01:42:37
【问题描述】:

我正在使用 React 和 Redux 开发一个应用程序。我有一个计时器 thunk,它每秒调度一个动作,并且状态会更新以表示实际时间。现在这对 UI 来说很棒,但我需要在特定时间播放声音,我不确定这个逻辑应该放在哪里。

我可以修改计时器 thunk 来播放声音,但这对我来说似乎不是一个好的解决方案,因为我认为计时器应该只负责调度“经过时间”的动作。

我的另一个想法是为商店订阅一个监听器,它将检查状态并在必要时播放声音。

【问题讨论】:

  • 你的第二个计划听起来很可靠。这样你就不会在你的 thunk 中产生副作用。

标签: javascript reactjs redux


【解决方案1】:

像这样使用sound 商店怎么样:

const initialState = {
  currentSound: undefined
}

export default function sound(state = initialState, action) {
  switch(action.type) {
    case UPDATE_TIME:
      const time = action.time
      const sounds = {
        6: '/sound1.mp3',
        22: '/sound2.mp3',
        99: '/sound3.mp3'
      }

      return Object.assign({}, state, {currentSound: sounds[time]})
  }
}

然后,在您的组件中,您可以使用react-redux 中的connect 来获取您的状态(state.sound.currentSound)并播放声音(如果有的话)。由于每次发送 action 都会更新 store,如果那段时间没有声音,currentSound 将是undefined。

【讨论】:

    猜你喜欢
    • 2012-07-31
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多