首页 > 解决方案 > ReactJS ProgressBar 值未与 state.progressValue 同步更新

问题描述

我目前正在使用 import { Progress } from 'react-sweet-progress'; ,在我也尝试过import { Progress } from 'reactstrap';仅使用 bootstrap 4 ProgressBar 之前。

我有一个维护progressValue的状态,并使用音频HTML标签来调用在线音频src并播放它。在timeupdateeventListener 期间,我在状态中更新我的 progressValue,并通过设置<Progress>as的值来反映它this.state.progressValue

class FooBar extends Component {
    state = {
         progressValue: 0
    }

    handleProgress = () => {
        this.currentTimeInterval = null;

        this.audio.onplay = () => {
            this.setState({
                progressValue: 0,
                play: true
            });

        this.audio.addEventListener('timeupdate', () => {
            this.setState({
                progressValue: Math.floor(this.audio.currentTime / this.audio.duration * 100)
            }, function() {
                console.log(this.state.progressValue);
            })
        }, true)

        this.audio.onpause = () => {
            clearInterval(this.currentTimeInterval);
        }
    }

    render() {
        return(
            <audio 
                ref={(audio) => { this.audio = audio }} 
                src={http://www.music.helsinki.fi/tmt/opetus/uusmedia/esim/a2002011001-e02.wav} 
                autoPlay 
                onLoadedData={this.handleProgress}
            />
            <Progress value={this.state.progressValue} />
        );
    }
}

但是,时间似乎与音频播放的位置不匹配,并且在音频将领先于 progressValue 的意义上,progressValue 将被延迟。因此,当音频结束时,progressBar 可能还需要 2~3 秒才能达到 100%。

我也试过:

this.currentTimeInterval = setInterval(() => {
    this.setState({
        progressValue: Math.floor(this.audio.currentTime / this.audio.duration * 100)
     }))
 }, 100)

并尝试将 100ms 的 timeInterval 操作为较小的数字,使其更接近但延迟仍然存在。

3个问题:

1)是什么导致这种情况发生?

2)有没有办法解决这个问题?

3) 如果对 2) 的回答是“否”,我是否可以使用另一个组件来显示音频文件的进度?(不是音频标签的默认值controls)。

谢谢!

标签: javascriptreactjsasynchronousaudioprogress-bar

解决方案


推荐阅读