以下是代码:
buildImgSuccess(json) {
if (typeof json !== "undefined") {
if (json.filesUploaded.length) {
//-- Update Saving Status --//
this.setState({
saving: true
});
//-- Set Vars --//
let item = 0;
let sortOrder = 0;
let imgCount = this.state.images.length;
if (!imgCount) {
imgCount = 0;
}
while (item < json.filesUploaded.length) {
//-- Determine if PDF Document was Uploaded --//
if (json.filesUploaded[item].mimetype === "application/pdf") {
//-- Handle Document Upload --//
//-- Get Number of pages --//
let theKey = json.filesUploaded[item].key;
let theHandle = json.filesUploaded[item].handle;
axios.get(`/getPhotos`, {
headers: {
"Content-Type": 'application/json'
},
transformRequest: (data, headers) => { delete headers.common.Authorization; }
}).then(jsonResult => {
let pageCount = 1;
我们的lint编译器正在产生此错误
Don't make functions within a loop
任何时候循环内都有.then()
或.catch()
。
是否有人了解此代码结构和任何可能的解决方案存在什么问题?
谢谢!
答案 0 :(得分:1)
您需要在while
循环之外创建函数。
创建内部会重新创建每个不具有性能的循环函数。
见下文。
简化示例 - 错误
const i = 0;
while (i < 10) {
const print = (i) => console.log(i++); //Created 10 times (0,1,...,8,9)
print(i);
};
简化示例 - 更正
const i = 0;
const print = (i) => console.log(i++); //Created once
while (i < 10) {
print(i);
};
使用您的代码
const handleJsonResult = (jsonResult) => {
let pageCount = 1;
//...
}
while (item < json.filesUploaded.length) {
//-- Determine if PDF Document was Uploaded --//
if (json.filesUploaded[item].mimetype === "application/pdf") {
//-- Handle Document Upload --//
//-- Get Number of pages --//
let theKey = json.filesUploaded[item].key;
let theHandle = json.filesUploaded[item].handle;
axios.get(`/getPhotos`, {
headers: {
"Content-Type": 'application/json'
},
transformRequest: (data, headers) => { delete headers.common.Authorization; }
}).then(handleJsonResult);
//...
}