情景展示:如上图所示:我的新增客户弹窗中引用了上传组件,当再次打开modal弹窗的时候,上一次上传的图片的缓存还在,这个问题问了问身边的大佬,最后解决了,
最简单的解决办法是:
给组件添加唯一的key值:
//在这里给key添加, Math.random()的得出来的是随机数
<div key={Math.random()}>
<Upload {...props} defaultFileList={this.state.fileList}>
<Button>
<Icon type="upload" onClick={this.upLoadImg}/> 上传
</Button>
</Upload>
</div>
Math.random()的得出来的是随机数,这样在每次打开弹窗的时候upload组件得到的key值都是唯一值
完整代码如下:包括组件的使用以及清除上一张上传的缓存
import {Upload} from 'antd';
export default class Customer extends React.Component{
this.state={
organCertUrl:"",//用来存放图片地址的对象
}
render(){
//------------------------------------定义上传图片的参数----------------------------------------
const $this=this
const props = {
ref:"upload",
action: '/safemgmt/api/custom/uploadOrganPic', //这块是将后台给你的接口地址需要复制到这一块
listType: 'picture',
className: 'upload-list-inline',
onChange({ file, fileList }) {//file,和fileList是组件自带的参数,根据你上面赋值过去的接口给你返回的内容,file是个对象,fileList是个数组,其实file对象就相当于你用axios方法返回的response对象差不多啦~
if (file.status === 'done') {
$this.setState({
organCertUrl:file.response.result,//前面是我的存放地址的对象
})
}
}
}
}
}
return(
<div>
//..........中间的其他内容省略,下面是上传组件内容
<div key={Math.random()}>
<Upload {...props} defaultFileList={this.state.fileList}>
<Button>
<Icon type="upload" onClick={this.upLoadImg}/> 上传
</Button>
</Upload>
</div>
</div>
)
作者:废柴码农
链接:https://www.jianshu.com/p/5c77b307f24c
来源:简书