javascript - ReactJS ProgressBar 值未与 state.progressValue 同步更新
问题描述
我目前正在使用
import { Progress } from 'react-sweet-progress';
,在我也尝试过import { Progress } from 'reactstrap';
仅使用 bootstrap 4 ProgressBar 之前。
我有一个维护progressValue的状态,并使用音频HTML标签来调用在线音频src并播放它。在timeupdate
eventListener 期间,我在状态中更新我的 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
)。
谢谢!
解决方案
推荐阅读
- node.js - 为什么我在终端中得到 ECONNRESET,但在浏览器中没有?
- java - Java 运行时版本
- javascript - 如何在 v-for 循环中匹配两个数组的并集
- r - Rmarkdown脚注和页面末尾之间的大空白空间
- javascript - Angular 6 readonly textarea 不会从第二个 textarea 绑定
- mongodb - AWS DocumentDB 是否支持在单个查询中加入 3 个以上的集合?
- python - 如何将 RFE 与 xgboost Booster 一起使用?
- c# - c# Oracle SQL 语句通配符
- r - 如何预测带有相关错误的 R 中整个数据库的未来销售?
- python - 遍历同一个列表两次以找到没有重复的数字