reactjs - Can I dispatch an action in reducer? -
is possible dispatch action in reducer itself? have progressbar , audio element. goal update progressbar when time gets updated in audio element. don't know place ontimeupdate eventhandler, or how dispatch action in callback of ontimeupdate, update progressbar. here code:
//reducer const initialstate = { audioelement: new audioelement('test.mp3'), progress: 0.0 } initialstate.audioelement.audio.ontimeupdate = () => { console.log('progress', initialstate.audioelement.currenttime/initialstate.audioelement.duration); //how dispatch 'set_progress_value' now? }; const audio = (state=initialstate, action) => { switch(action.type){ case 'set_progress_value': return object.assign({}, state, {progress: action.progress}); default: return state; } } export default audio;
dispatching action within reducer anti-pattern. reducer should without side effects, digesting action payload , returning new state object. adding listeners , dispatching actions within reducer can lead chained actions , other side effects.
sounds initialized audioelement
class , event listener belong within component rather in state. within event listener can dispatch action, update progress
in state.
you can either initialize audioelement
class object in new react component or convert class react component.
class myaudioplayer extends react.component { constructor(props) { super(props); this.player = new audioelement('test.mp3'); this.player.audio.ontimeupdate = this.updateprogress; } updateprogress () { // dispatch action reducer updated progress. // might want send current time , // calculation within reducer. this.props.updateprogress(); } render () { // render audio player controls, progress bar, whatever else return <p>progress: {this.props.progress}</p>; } } class mycontainer extends react.component { render() { return <myaudioplayer updateprogress={this.props.updateprogress} /> } } function mapstatetoprops (state) { return {}; } return connect(mapstatetoprops, { updateprogressaction })(mycontainer);
note updateprogressaction
automatically wrapped dispatch
don't need call dispatch directly.
Comments
Post a Comment