我正在使用react.js将XML文件发送到服务器,并且我想渲染一个加载器,直到服务器做出响应。
我尝试使用一个文件组件,它可以工作。但是我想用三个不同的文件制作文件,每个文件的大小和响应时间都不同。
我有这样的东西。
class UploadFiles extends Component {
state = {
isLoading: null }
// Omitted code for upload files to the state
uploadData(file){
// Omitted Code <- Asynchronous function, each file has a different
response time.
}
handleSubmit(){
this.setState({isLoading:true}, () => {
uploadData(file1).then(res => {
// Do something with the response
this.setState({isLoading: false});
}
this.setState({isLoading:true}, () => {
uploadData(file2).then(res => {
// Do something with the response
this.setState({isLoading: false});
}
this.setState({isLoading:true}, () => {
uploadData(file3).then(res => {
// Do something with the response
this.setState({isLoading: false});
}
}
render() {
return (
const {isLoading} = this.state;
if(isLoading){
return <Loader/>
}else {
return (
<div>
<FileComponent />
<FileComponent/>
<FileComponent/>
<button onClick={this.handleSubmit.bind(this)}>submit</button>
</div> );}
}
}
这种方法有效,但是如果将file1上传到服务器的速度比其他两个文件更快,则Loader组件仍不会呈现。 我需要加载器仍然呈现,直到将三个文件上传到服务器。
有什么正确/干净的方法可以做到这一点? 注意:我需要将文件一一发送到服务器。服务器每个请求仅收到一个文件。
答案 0 :(得分:3)
您正在生成3个并行的上载,并且您已经观察到第一个完成的集isLoading = false
。
要等待多个承诺,请像这样使用Promise.all:
this.setState({isLoading:true}, () => {
Promise
.all([
uploadData(file1)
uploadData(file2),
uploadData(file3)
])
.then(() => {
this.setState({isLoading:false})
})
});