程序员antd

antd引用<Upload>组件上传图片后再次上传清

2018-12-07  本文已影响388人  废柴码农
19_11_37__12_06_2018.jpg
情景展示:如上图所示:我的新增客户弹窗中引用了上传组件<Upload>,当再次打开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值都是唯一值

完整代码如下:包括<Upload>组件的使用以及清除上一张上传的缓存

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>
)
如果还有其他问题,欢迎留言~

PS:本人只是一枚废柴小码农,在实战中积累经验,只是将所踩过的坑分享出来给遇到同样坑的小伙伴们提个醒,可能会少走些弯路。如果能帮助到你解决实际问题,我将更加坚定分享的初衷:一起成长。
目前只在知乎上和简书上更新文章,准备在这两个地方持续更新文章,您的关注对我可能是莫大的鼓励。

知乎用户名:废柴码农
微博用户名:执拗病患者

哈哈,交个朋友啦~

上一篇 下一篇

猜你喜欢

热点阅读