我正在使用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组件。我需要在三个文件上传到服务器之前仍然呈现加载器。
有一些正确/干净的方法来做到这一点?注意:我需要将文件逐个发送到服务器。服务器每个请求只接收一个文件。
您正在产生3个并行上传,并且您已经观察到第一个完成设置isLoading = false
。
要等待几个承诺,请像这样使用Promise.all:
this.setState({isLoading:true}, () => {
Promise
.all([
uploadData(file1)
uploadData(file2),
uploadData(file3)
])
.then(() => {
this.setState({isLoading:false})
})
});