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

前端 未结 3 1280
温柔的废话
温柔的废话 2020-12-30 14:24

I\'m using 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

相关标签:
3条回答
  • 2020-12-30 14:49

    You need to bind the getData():

    function getData(result) {
        console.log(result); // displays whole data
        this.setState({data: result}); // but gets error here
    }.bind(this)
    
    0 讨论(0)
  • 2020-12-30 14:58

    You can try react-papaparse for an easy way. For more detail about react-papaparse please visit react-papaparse. Thanks!

    0 讨论(0)
  • 2020-12-30 15:08

    The problem:

    You try to call this.setState in the function getData. But this does not exist in the context of this function.

    The solution:

    I would try to not write function in functions, but write the functions in the class.

    You class could look like this:

    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;
    
    0 讨论(0)
提交回复
热议问题