在 react.js 中将文件发送到服务器时呈现加载程序
Render a loader while files are sent to the server in react.js
我正在使用 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 上传到服务器的速度比其他两个文件快,则加载程序组件仍未呈现。
我需要加载程序仍然呈现,直到三个文件上传到服务器。
有什么correct/clean方法可以做到这一点?
注意:我需要将文件一个一个发送到服务器。服务器每次请求只接收一个文件。
您正在生成 3 个并行上传,正如您已经观察到的第一个完成集 isLoading = false
。
要等待多个承诺,请像这样使用 Promise.all:
this.setState({isLoading:true}, () => {
Promise
.all([
uploadData(file1)
uploadData(file2),
uploadData(file3)
])
.then(() => {
this.setState({isLoading:false})
})
});
我正在使用 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 上传到服务器的速度比其他两个文件快,则加载程序组件仍未呈现。 我需要加载程序仍然呈现,直到三个文件上传到服务器。
有什么correct/clean方法可以做到这一点? 注意:我需要将文件一个一个发送到服务器。服务器每次请求只接收一个文件。
您正在生成 3 个并行上传,正如您已经观察到的第一个完成集 isLoading = false
。
要等待多个承诺,请像这样使用 Promise.all:
this.setState({isLoading:true}, () => {
Promise
.all([
uploadData(file1)
uploadData(file2),
uploadData(file3)
])
.then(() => {
this.setState({isLoading:false})
})
});