在写我的项目的时候,应用到了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>