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

2023-11-20

我在用着帕帕·帕斯解析 CSV 文件中的图表。我想将数据存储在反应状态文件解析后。 Papa.Parse() 不返回任何内容,结果异步提供给回调函数。此外,setState() 在异步回调中不起作用。这个问题类似于从 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);
}

Here's the error I get when I set state inside getData(). enter image description here

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

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


问题:

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

解决方案:

我会尝试不在函数中编写函数,而是在类中编写函数。

你的课程可能看起来像这样:

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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐