我正在研究一个Reactjs项目。在项目中我有一个场景,比如我需要从本地读取一个csv文件并将其转换为json对象。我正在使用csvtojson节点包将csv文件转换为json对象。请参阅以下代码:
import React from 'react';
import ReactDOM from 'react-dom';
var objects;
var ReadFile = React.createClass({
readFile:function(){
var file = this.refs.file.files[0];
var reader = new FileReader();
reader.onload = function(evt){
var resultText = evt.target.result;
objects = this.csvToJson(resultText);
console.log(objects);
}.bind(this);
var newFile = file.slice(0,5000);
reader.readAsText(newFile);
},
csvToJson:function(csvString){
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
converter.fromString(csvString, function(err,result){
//When i console log the result it is working but when i return The result:
// i am getting a undefined error
//console.log(result);
return result;
});
},
render:function(){
return (
<input type="file" ref="file" onChange={this.readFile} />
);
}
});
ReactDOM.render(<ReadFile />,document.getElementById('container'));
当我控制台记录 csvToJson 文件的结果时,我收到一个未定义的错误。请有人指导我,我做错了什么?
答案 0 :(得分:3)
import React, { Component } from 'react'
import { connect } from 'react-redux'
import ReactFileReader from 'react-file-reader';
export default class CsvRead extends React.Component {
constructor(props) {
super(props);
}
handleFiles = files => {
var reader = new FileReader();
reader.onload = function(e) {
// Use reader.result
var csv = reader.result;
var lines = csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
result= JSON.stringify(result); //JSON
console.log(result);
}
reader.readAsText(files[0]);
}
render() {
return (
<ReactFileReader handleFiles={this.handleFiles} fileTypes={'.csv'}>
<button className='btn'>Upload</button>
</ReactFileReader>
);
}
}
这样可以正常工作。