简体   繁体   中英

react-sound - Force React Component to update and go to position?

I am trying to build an audio player using react-sound. I want to implement a feature wich simply goes back to a certain position in the audio.

I simply do this for now:

goToVeryCustomPosition() {
  this.setState({playFromPosition: this.state.myVeryCustomPosition});
}

My problem is this: This works -but it only works once . The sound will go back to the position specified, but if I want to do this two times in a row, it won't work.

I guess this is because my component is not updated since the position is still the same. When I set it first, it changes from position 0 (in the constructor), to position 233 (or whatever it might be). When I then call the thing again, it will still be 233, since this is what I want to do. But since this is the same as the previous state, React won't update. How could I solve this?

edit: the rest of the component.

constructor:

constructor(props) {
    super(props);

    this.state = {
       playStatus: Sound.status.STOPPED,
       elapsed: 0,
       total: 0,
       playFromPosition: 0,
       myVeryCustomPosition: 1337.727
     }
  }

render & handleSongPlaying:

handleSongPlaying(audio){
     this.setState({
                      position: audio.position,
                      elapsed: audio.position,
                      total: audio.duration})
   }

  render() {
    return (
      <div className="row handle">
        <Sound
            url="./sound.mp3"
            playStatus={this.state.playStatus}
            onPlaying={this.handleSongPlaying.bind(this)}
            playFromPosition={this.state.playFromPosition}
            />

        <button onClick={this.togglePlay.bind(this)}>Play / Pause</button>
        <button onClick={this.repeat.bind(this)}>Replay</button>
      </div>
    );
  }
}

You can use a forceUpdate

goToVeryCustomPosition() {
    if(this.state.playFromPosition != this.state.myVeryCustomPosition) {
        this.setState({playFromPosition: this.state.myVeryCustomPosition});
    } else {
        this.forceUpdate()
    }
}

One more thing you can do is have a separate state variable like isUpdating . Where you set the this.state.myVeryCustomPosition set isUpdating to true and in the goToVeryCustomPosition set it to false .

This way it will always update and you will not have to use forceUpdate which is slightly frowned upon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM