在我的redux商店中添加一个`new Audio`元素

时间:2017-11-22 15:36:07

标签: javascript reactjs ecmascript-6 redux

我正在尝试向我的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>
         );
      });
    }
};

1 个答案:

答案 0 :(得分:1)

什么是Audio对象?

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

而不是这样做:

audioPlaying: new Audio(action.song.url)

这样做:

audioPlaying: action.song.url

我可以看到你的redux状态不是一成不变的,这可能会在以后引起你的一些问题。我建议你使用像Immutable.js这样的库来解决这个问题。