- 说明:在使用Antd 的 Upload 组件 的onChange()方法中,打印fileList 中的文件状态status 一直是 uploading,无法拿到上传文件后服务端响应的内容,且组件下方不显示文件列表问题,以下是解决方法:
const Dragger = Upload.Dragger;
constructor(props) {
super(props);
this.state = {
fileList: [],
};
}
<Dragger
listType={"picture"}
action={uploadUrl}
accept={acceptPictype}
disabled={upLoadDisabled}
beforeUpload={() => {
}}
fileList={isScanSuccess?[]:this.state.fileList}
onChange={
(data) => {
console.log(data)
const { fileList, file } = data;
//自己的逻辑
this.setState({ fileList: [...fileList] });//这段代码放在处理逻辑的最后面
}
}
}
>
在github[解答](https://github.com/ant-design/ant-design/issues/2423)上此问题解答:
对于受控模式,你应该在 onChange 中始终 setState fileList,保证所有状态同步到 Upload 内。类似这里的写法:http://ant.design/components/upload/#components-upload-demo-fileList
// good 正确写法
onFileChange(fileList) {
if ( ... ) {
...
} else {
...
}
// always setState
this.setState({ fileList: [...fileList] });
}
<Upload fileList={this.state.fileList} onChange={this.onFileChange} />
// bad 写法
onFileChange(fileList) {
if ( ... ) {
this.setState({ fileList: [...fileList] });
} else {
...
}
}
<Upload fileList={this.state.fileList} onChange={this.onFileChange} />
建议研习受控组件概念:https://facebook.github.io/react/docs/forms.html#controlled-components
注意需要克隆 fileList 以保障 Upload 能感知数组变化。
- this.setState({ fileList });
+ this.setState({ fileList: [...fileList] });