我正在创建一个图片转换器,其中我的JS代码从用户那里获取文件输入,并将其发送到我的python后端,在此处将它们转换并保存到文件夹中。然后,Python将响应发送回JS(反应),该响应将JS分别更新为“已转换”,并重新提供必要的组件。
我有一个for循环,可为每个文件发送单独的POST请求。很好,直到在所有文件都转换后我想为整个目录创建.zip为止。我的问题就在那里。我的zip总是返回为空或文件不完整。
// function which takes the file inputs from user
uploadBatch = async () => {
const files = this.getFilesFromInput();
const batch = Math.floor(Math.random() * 999999 + 100000);
for (let i = 0; i < files.length; i++) {
// sets the state which will then be updated
await this.setState(
{
files: [
...this.state.files,
{
// file state values
}
]
},
() => {
const formData = new FormData();
// appends stuff to form data to send to python
axios
.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
responsetype: 'json'
})
.then(response => {
// update the state for this particular file
});
}
);
}
return batch;
};
// function which zips the folder after files are converted
handleUpload = async e => {
e.preventDefault();
// shouldn't this next line wait for uploadBatch() to finish before
// proceeding?
const batch = await this.uploadBatch();
// this successfully zips my files, but it seems to run too soon
axios.post('/api/zip', { batch: batch }).then(response => {
console.log(response.data);
});
};
我已经使用了async / await,但是我认为我没有很好地使用它们。我不太了解这个概念,因此请您多加解释。
答案 0 :(得分:1)
无论何时调用setState()
,组件都会重新渲染。理想情况下,您应该完成所有操作并最后致电setState()
。
这样的事情应该可以为您工作
// function which takes the file inputs from user
uploadBatch = async () => {
const files = this.getFilesFromInput();
const batch = Math.floor(Math.random() * 999999 + 100000);
const files = [];
for (let i = 0; i < files.length; i++) {
const formData = new FormData();
// appends stuff to form data to send to python
const res =
await axios
.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
responsetype: 'json'
});
files.push('push data into files arr');
}
return { files, batch };
};
// function which zips the folder after files are converted
handleUpload = async e => {
e.preventDefault();
// get batch and files to be uploaded and updated
const { files, batch } = await this.uploadBatch();
// this successfully zips my files, but it seems to run too soon
await axios.post('/api/zip', { batch: batch }).then(response => {
console.log(response.data);
});
// set the state after all actions are done
this.setState( { files: files });
};