我正在尝试渲染使用react上传的文件中的十六进制值。 当我上传大文件(例如 10MB)时,页面崩溃,但像 http://mikach.github.io/hex-editor/ 这样的网站奇迹般有效。我不明白我做错了什么。
下面是执行相同操作的代码
import React from "react";
class App extends React.PureComponent {
constructor(props) {
super(props);
this.fileReader = null;
this.state = {
filecontent: [],
decodingSection: [
{ type: "BigUint64", startIndex: "0", endIndex: "0" },
{ type: "BigUint64", startIndex: "0", endIndex: "0" }
]
};
}
handleFileRead = () => {
const typedArray = new Uint8Array(this.fileReader.result);
const untypedArrray = [];
const iii = typedArray.values();
while (true) {
const { value, done } = iii.next();
if (done) {
break;
}
const hexValue = value.toString(16);
untypedArrray.push(hexValue.length === 1 ? `0${hexValue}` : hexValue);
}
this.setState({
filecontent: untypedArrray
});
};
handleFileChosen = file => {
this.fileReader = new FileReader();
this.fileReader.onloadend = this.handleFileRead;
this.fileReader.readAsArrayBuffer(file);
};
render() {
return (
<div>
<input
type={"file"}
id={"file"}
onChange={e => this.handleFileChosen(e.target.files[0])}
/>
<br />
{this.state.filecontent.length > 0 && (
<div>No Bytes present {this.state.filecontent.length}</div>
)}
{this.state.filecontent.map(each => `${each} `)}
</div>
);
}
}
export default App;
最佳答案
一个可能的原因可能是渲染方法中的 map this.state.filecontent.map(each => '${each} ')
,我想我不确定。
我稍微修改了代码,以便它将整个字符序列保存到一个名为 contents
的字符串中(使用数组的 join 方法),然后立即渲染它。
您可以看看并尝试一下here 。至少,它对我来说对 10Mb 文件有效:)
关于javascript - 如何在react.js中高效处理大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59687702/