【antd 的Upload组件onChange方法只执行一次file.status===‘uploading‘,走不到‘done‘的原因和解决方法】

2023-11-12

背景:如下图所示,使用antd的Upload组件实现上传视频和图片,实现自定义的加载中和预览效果。

上传中:(loading状态)
在这里插入图片描述
上传完毕:(done状态)
在这里插入图片描述
实现文件上传中loading思路: 当文件在上传中会执行onChange的回调,在file.status === 'uploading'时展示loading中,在file.status === 'done'预览文件。

import React, {Component} from 'react'
import {Upload} form 'antd'
export default class UploadFile extends Component {
	state = {
		loading: false,
		fileList: []
	}
	onChange = (info) => {
		const {file: {status}, fileList} = info
		if(status === 'uploading') {
			this.setState({loading: true})
		}
		if(status === 'done') {
			this.setState({loading: false})
		}
	}
	render() {
		const {fileList} = this.state
		return (
			<Upload onChange={this.onChange} fileList={fileList}/>
		)
	}
} 

以上代码执行时只会执行一次onChangefile.status === 'uploading',这里调用了this.setState({loading: true}),setState导致组件重新渲染,< Upload />组件重新请求时fileList=[]导致请求中断,即不会再次执行onChange,也就不会走到file.status === 'done' 中。

解决方法:

const {file: {status}, fileList} = info
if(status === 'uploading') {
	this.setState({loading: true, fileList:[...fileList]})
}

Upload组件继续上次的请求。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【antd 的Upload组件onChange方法只执行一次file.status===‘uploading‘,走不到‘done‘的原因和解决方法】 的相关文章

随机推荐