Ama*_*ria 6 javascript csv json reactjs papaparse
我正在使用Papa Parse解析Graphs的CSV文件.我希望在解析文件后将数据存储在React状态.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);
}
Run Code Online (Sandbox Code Playgroud)
数据在getData()中可用,但我想提取它.
我应该如何将数据存储在状态或其他变量中,以便我可以将其用于图形?
Lar*_*rce 10
问题:
您尝试在函数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;
Run Code Online (Sandbox Code Playgroud)