我正在尝试向我的redux存储添加new Audio元素。

我有一个减速器看起来像这样:

export const songsReducer = (state = {}, action) => {

    switch (action.type) {
        case "PLAY_SONG":
           return {
             ...state,
             songPlaying: true,
             songDetails: action.song,
             audioPlaying: new Audio(action.song.url)
        }


        case "STOP_SONG":
            return {
              ...state,
              songPlaying: false,
              songDetails: null
            }

        default:
          return state;
    }

};

export default songsReducer;


但是,当我检查我的redux存储audioPlaying是一个像{}这样的空对象时

有人可以告诉我我在做什么错吗?

我称之为动作的组件在这里

class Audio extends Component {

    static audio;

    playSong = (song) => {
        if(!this.props.audioPlaying){
            this.props.playSong(song);
            // I want to move the following lines out of the
            // component as I need to control the audio from elsewhere in the app
            // this.audio = new Audio(song.url);
            // this.audio.play();
        } else {
            this.props.songsReducer.audio.pause();
            this.props.playSong(song);
            // this.audio = new Audio(song.url);
            // this.audio.play();
        }
    }

    render() {
       this.props.songs.map(song => {
         return (
           <li onClick={(song) => this.playSong(song)}>Play { song.name }</li>
         );
      });
    }
};

最佳答案

什么是Audio对象?

否则,我建议将正在播放的歌曲直接存储在属性audioPlaying中。我假设action.song.url是歌曲URL的字符串。

而不是这样做:

audioPlaying: new Audio(action.song.url)


做这个:

audioPlaying: action.song.url


如我所见,您的redux状态不是一成不变的,这可能会在以后给您带来一些问题。我建议您使用Immutable.js之类的库来解决该问题。

09-12 07:47