【发布时间】:2021-05-20 10:38:36
【问题描述】:
我对 reactjs 很陌生。目前,我正在开发一个需要迭代读取一些文件的项目。所以我将一些文件传递给 fileHandlingFunction。
export class MainComponent extends React.Component {
constructor(){
this.state = {
imageFiles: [];
}
}
fileHandlingFunction(files){ // files is an array of image files
// iterate through the files and append them into an array in state
this.syncIterate(files, this.syncIterate);
}
syncIterate(fileArray, callBackSyncIterate) {
let tempFile = fileArray[0];
const reader = new FileReader();
reader.readAsDataURL(tempFile);
reader.onload = (event) => {
this.setState({imageFiles: this.state.imageFiles.concat[reader.result]});
}
if (fileArray.length > 1) {
// Removes the first element of the file array
let updatedArray = fileArray.slice(1);
callBackSyncIterate(updatedArray, callBackSyncIterate);
}
}
}
当我使用 for 循环将文件附加到状态时,先附加较小的文件,然后附加较大的文件(我严格需要避免这种情况)。这就是使用回调函数以递归方式遍历传递给 fileHandlingFunction 的 files 数组的原因。
但是当我尝试在递归函数调用中插入图像文件时,我得到 “Uncaught TypeError: Cannot read property 'setState' of undefined” 错误。 在这个阶段,我们不能在递归函数调用中改变组件的状态。我希望您提出解决此问题的建议。 我非常感谢您为解决此问题所提供的帮助。提前致谢。
【问题讨论】:
-
我认为问题在于您的函数将
this读取为未定义。所以要将函数转换为箭头函数。 -
@PriyankKachhela 我用箭头函数试过了。但后来我又遇到了同样的问题。首先附加较小的文件,然后附加较大的文件。
标签: javascript reactjs react-native