javascript - 如何在react.js中高效处理大文件

标签 javascript reactjs

我正在尝试渲染使用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/

相关文章:

javascript - React 有望在全局范围内可用

javascript - react : If Else logic, 大于 100

javascript - Socket.io 未发出超过 1 个事件

javascript - 使用 oracle jet + knockout JS + elasticsearch 根据用户列选择填充动态列

javascript - .filter() 中的函数无法正常工作

javascript - 将其传递到 map 上的点击处理程序中

reactjs - 在react-redux-form中,如何禁用提交按钮,直到所有必填字段都未填写

javascript - 可以消除浏览器编译错误并显示 react 错误边界吗?

javascript - JQuery Ajax 将 html 数据发布到 php 并获得回复

javascript - "You may need an appropriate loader to handle this file type"