首页 > 解决方案 > 尝试使用 react-papaparse 逐行流式传输本地文件,但它不起作用 - 我是正确编码还是不可能?

问题描述

我可以使用 react-papaparse 解析触发 onFileLoad={this.handleOnFileLoad} 的本地文件,但我想流式传输它,所以我尝试了下面的代码,尝试传递 onStep 或 step in props 但它没有触发。该文档暗示这是可能的,但我是否以错误的方式进行此操作?我想一次处理每一行,以防它是一个非常大的文件。谢谢。

import React from 'react';
import { CSVReader } from 'react-papaparse';

const buttonRef = React.createRef();

export default class CSVReader1 extends React.Component {
  handleOpenDialog = (e) => {
    // Note that the ref is set async, so it might be null at some point
    if (buttonRef.current) {
      buttonRef.current.open(e);
    }
  };
  handleOnStep = (row) => {
    console.log('handleOnComplete---------------------------');
    console.log(row);
    console.log('---------------------------');
  };
  handleOnError = (err, file, inputElem, reason) => {
    console.log('handleOnError---------------------------');
    console.log(err);
    console.log('---------------------------');
  };
  handleOnRemoveFile = (data) => {
    console.log('handleOnRemoveFile---------------------------');
    console.log(data);
    console.log('---------------------------');
  };
  handleRemoveFile = (e) => {
    // Note that the ref is set async, so it might be null at some point
    if (buttonRef.current) {
      buttonRef.current.removeFile(e);
    }
  };
  render() {
    return (
      <CSVReader
        ref={buttonRef}
        onError={this.handleOnError}
        onStep={this.handleOnStep}
        noClick
        noDrag
        onRemoveFile={this.handleOnRemoveFile}
      >
        {({ file }) => (
          <div className="form">
            <div>
              <button className="button" type="button" onClick={this.handleOpenDialog} >Browse file</button>
            </div>
            <div className="text-input">
              {file && file.name}
            </div>
            <div>
              <button className="button button--secondary" onClick={this.handleRemoveFile}>Remove</button>
            </div>
          </div>

        )}
      </CSVReader>

    );
  };
}

标签: reactjsstreampapaparse

解决方案


如果您定义了 astepcomplete处理程序,则onFileLoad不会调用 。

源行

config?.complete || config?.step
          ? config.complete
          : () => {
              if (!onDrop && onFileLoad) {
                onFileLoad(data, file);
              } else if (onDrop && !onFileLoad) {
                onDrop(data, file);
              }
            }

推荐阅读