共计 2039 个字符,预计需要花费 6 分钟才能阅读完成。
在写我的项目的时候,应用到了 antd 外面的 Upload 来上传文件,写好之后运行报错。。。
代码是这样的:
const uploadProps = {action: createTheURL('software/stu/score', 'upload'), | |
method: 'POST', | |
headers: {authorization: tokenHandler.getSessionByKey('authorization') | |
}, | |
onRemove: this.handleRemove | |
} | |
<Form.Item | |
label='附件' | |
>{getFieldDecorator('appendix', {initialValue: JSON.parse(appendix) || [], | |
valuePropName: 'fileList', | |
})(<Upload {...uploadProps} > | |
<a style={{marginRight: 20}}> | |
<Icon type="plus" /> 增加附件 | |
</a> | |
<span>(最多上传 10 个文件,单个文件不能超过 20M)</span> | |
</Upload>)} | |
</Form.Item> |
造成这个问题的起因是,因为在上传了一个文件之后,会有产生一个新的 fileList,然而这个新的 fileList 没有回传到 Upload 组件的 fileList 外面,所以只有咱们把新的 fileList 给到 Upload,那么这个问题就能够解决了。
最开始我的做法是,将 fileList 存到 state 外面,而后每次上传文件就会触发 Upload 的 onChange 函数,在 onChange 函数外面将新的 fileList 又通过应用 setState 将其存到 state 外面,最初在将 state 外面的 fileList 放到 Upload 外面。
代码大略就是这个样子:
handleChange = info => {const { fileList} = info; | |
this.setSate({fileList}); | |
} | |
render(){const { fileList} = this.state; | |
const uploadProps = {action: createTheURL('software/stu/score', 'upload'), | |
method: 'POST', | |
headers: {authorization: tokenHandler.getSessionByKey('authorization') | |
}, | |
fileList, | |
onRemove: this.handleRemove, | |
onChange: this.handleChange | |
}; | |
return ( | |
<Form.Item | |
label='附件' | |
> | |
<Upload {...uploadProps} > | |
<a style={{marginRight: 20}}> | |
<Icon type="plus" /> 增加附件 | |
</a> | |
<span>(最多上传 10 个文件,单个文件不能超过 20M)</span> | |
</Upload> | |
</Form.Item> | |
) | |
} |
然而这样写,在前面还是会有一些问题,这里只用来解决新增表单数据没问题;然而如果是要对上传之后的表单数据进行一个批改的话就会呈现问题,因为在批改的时候,须要先获取曾经提交了的数据,对于曾经上传了的文件须要先获取到文件名,生成 fileList 存到 state 外面,而后再放到 Upload 组件外面,如果这样写的话,最初就会发现整个流程就很凌乱,而且也不肯定齐全没问题。
最终解决办法:
间接应用 antd Form 组件外面的 getValueFromEvent 办法,这个办法的作用就是把 onChange 的参数 (Upload 外面,这里的参数就是 file 和 fileList)。
antd Form 组件
我写的代码如下:
const uploadProps = {action: createTheURL('software/stu/score', 'upload'), | |
method: 'POST', | |
headers: {authorization: tokenHandler.getSessionByKey('authorization') | |
}, | |
onRemove: this.handleRemove | |
} | |
<Form.Item | |
label='附件' | |
>{getFieldDecorator('appendix', {initialValue: JSON.parse(appendix) || [], | |
valuePropName: 'fileList', | |
getValueFromEvent: e => {if (Array.isArray(e)) {return e;} | |
return e && e.fileList; | |
} | |
})(<Upload {...uploadProps} > | |
<a style={{marginRight: 20}}> | |
<Icon type="plus" /> 增加附件 | |
</a> | |
<span>(最多上传 10 个文件,单个文件不能超过 20M)</span> | |
</Upload>)} | |
</Form.Item> |
正文完
发表至: javascript
2021-04-28