reactjs - 向弹出通知传递正确的属性
我想显示一个包含上传状态的通知。我接手了一个使用 React 和 ASP.NET 的项目,而我对此还比较陌生。问题非常简单,但我一直在努力解决它:我如何显示一个弹出通知,显示哪些文件已成功上传,哪些没有?
import * as React from "react";
import { connect } from "react-redux";
import { Form, Select, Button, Upload, message, notification} from 'antd';
import * as Actions from "../actions";
const FormItem = Form.Item;
class UploadFileForm extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
handleSubmit = (e) => {
message.config({ top: 0 });
message.loading('Importing in progress...', 3);
e.preventDefault();
this.props.uploadFile(this.props.form.getFieldsValue());
notification["info"]({
message: 'Files successfully uploaded',
description: '', // <-- this line has to be modified
duration: 10
});
}
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form onSubmit={this.handleSubmit}>
<FormItem label="File" >
{getFieldDecorator('upload', {
valuePropName: 'fileList',
getValueFromEvent: (e) => e.fileList.slice(-1)
})(
<Upload name="importFile" action={' '} multiple={false}>
<Button> Upload </Button>
</Upload>
)}
</FormItem>
<Button type="primary" htmlType="submit">Import</Button>
</Form>
);
}
}
export default Form.create()(UploadFileForm);
更具体地说:我必须如何修改这一行 description: '', 才能以纯文本显示所有已上传文件及其状态,例如 File(s) '1.txt', '2.txt', and '3.txt' 已成功上传。File(s) '4.txt' 上传失败。?
项目文档说我们在使用 Redux-Saga,但我没有,所以也许这会让这个故事更容易理解。
答案#1
我猜你的 this.props.uploadFile 方法是一个 promise,所以考虑到这一点,你应该在该 promise 被解决后显示通知
this.props.uploadFile(this.props.form.getFieldsValue()).then(result => {
// since your client doesn't know which ones are success/failed, server should return
// this information when request is finished
const { successUploads, failUploads } = result;
notification["info"]({
message: 'Files successfully uploaded',
description: `File(s) ${successUploads.join(', ')} have been successfully uploaded. File(s) ${failUploads.join(', ')} failed.`
duration: 10
});
});
如果你无法控制从服务器返回的内容,那么你需要在客户端跟踪上传,但那意味着需要向服务器进行多次上传(请求),而你的上传方法可能看起来像这样:
async function uploadFiles(files) {
// I've called your server upload uploadService.send(), but replace this with your method
const results = await Promise.all(
files.map(file => uploadService.send(file))
.map(p => p.catch(e => e)
);
let successUploads = [];
let failUploads = [];
results.forEach((result, idx) => {
const file = files[idx];
if (result instanceof Error) {
failUploads.push(file);
} else {
successUploads.push(file);
}
});
return {
successUploads,
failUploads
}
}
然后你可以像第一个代码片段中那样调用 uploadFiles。
