如何使用 Papa Parse 从 CSV 文件中将数据提取到 React 状态?

How to extract data to React state from CSV file using Papa Parse?

我正在使用 Papa Parse to parse a CSV file for Graphs. I want to store the data in React state after the file is parsed. Papa.Parse() doesn't return anything and results are provided asynchronously to a callback function. Also, setState() doesn't work inside a async callback. This question is similar to Retrieving parsed data from CSV

我尝试使用以下代码将数据存储在状态中,但正如预期的那样,它不起作用。

componentWillMount() {

    function getData(result) {
      console.log(result); //displays whole data
      this.setState({data: result}); //but gets error here
    }

    function parseData(callBack) {
      var csvFilePath = require("./datasets/Data.csv");
      var Papa = require("papaparse/papaparse.min.js");
      Papa.parse(csvFilePath, {
        header: true,
        download: true,
        skipEmptyLines: true,
        complete: function(results) {
          callBack(results.data);
        }
      });
    }

    parseData(getData);
}

这是我在 getData() 中设置状态时遇到的错误。

数据在 getData() 中可用,但我想提取它。

我应该如何将数据存储在状态或其他变量中以便我可以将其用于图形?

问题:

您尝试在函数 getData 中调用 this.setState。但这在此函数的上下文中不存在。

解决方法:

我尽量不在函数中写函数,而是在class中写函数。

你 class 可能看起来像这样:

import React, { Component } from 'react';

class DataParser extends Component {

  constructor(props) {
    // Call super class
    super(props);

    // Bind this to function updateData (This eliminates the error)
    this.updateData = this.updateData.bind(this);
  }

  componentWillMount() {

    // Your parse code, but not seperated in a function
    var csvFilePath = require("./datasets/Data.csv");
    var Papa = require("papaparse/papaparse.min.js");
    Papa.parse(csvFilePath, {
      header: true,
      download: true,
      skipEmptyLines: true,
      // Here this is also available. So we can call our custom class method
      complete: this.updateData
    });
  }

  updateData(result) {
    const data = result.data;
    // Here this is available and we can call this.setState (since it's binded in the constructor)
    this.setState({data: data}); // or shorter ES syntax: this.setState({ data });
  }

  render() {
    // Your render function
    return <div>Data</div>
  }
}

export default DataParser;

你可以试试react-papaparse for an easy way. For more detail about react-papaparse please visit react-papaparse。谢谢!

您需要绑定 getData():

function getData(result) {
    console.log(result); // displays whole data
    this.setState({data: result}); // but gets error here
}.bind(this)