在React中显示快速变化值的推荐方法是什么,例如上传进度?在我的axios配置中我有 onUploadProgress: progressEvent = { let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ) this.set
onUploadProgress: progressEvent => { let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ) this.setState({ avatarUploadPercentage: percentCompleted }) }
< span>上传进度:{this.state.avatarUploadProgress}< / span>
但是setState当然不喜欢被快速调用,并且不保证顺序.我应该使用refs而不是自己更改内部html吗?
如何限制onUploadProgress回调运行的时间?您可以将回调包装在“去抖动”功能中,该功能可以限制回调运行的频率. Underscore和 Lodash提供去抖方法.每秒一次:
onUploadProgress: debounce(progressEvent => { let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ) this.setState({ avatarUploadPercentage: percentCompleted }) }, 1000)
请参阅https://davidwalsh.name/javascript-debounce-function的普通去抖功能.