我有一个简单的 react 组件,允许用户使用react-csv-reader上传csv文件,然后将其上传到数据库。如何将csv数据分配给react中的状态?当我从 state 读取数据时,遇到错误 Import.jsx:23 Uncaught TypeError: Cannot read property 'state' of undefined
。
import React from "react";
import axios from "axios";
import PropTypes from 'prop-types';
import CSVReader from "react-csv-reader";
import "assets/css/import.css";
class Import extends React.Component {
constructor(props) {
super(props);
this.state = {data:[]};
}
handleForce = data => {
console.log(data.length);
console.log(data);
this.setState({data: data});
};
handleClick() {
console.log("success");
console.log(this.state.data);/*this is where error occur*/
}
render() {
return (
<div className="container">
<CSVReader
className="csv-input"
label="Select CSV file to import"
onFileLoaded={this.handleForce}
/>
<div>
</div>
<button onClick={this.handleClick}>
Upload
</button>
</div>
);
}
}
Import.propTypes = {
classes: PropTypes.object.isRequired,
};
export default Import;
它成功地在控制台的 console.log(data.length);
和 console.log(data);
行打印。但是,我认为它无法将 csv 数据分配给状态。
这是控制台成功打印的csv数据。
0: (11) ["identifier", "postal", "volume", "weight", "service_time", "phone", "customer_name", "window_start", "window_end", "lat", "lng"]
1: (11) ["SN48164550", "089952", "1", "1", "15", "90648664", "Customer 860", "2018-10-11 10:00:00", "2018-10-11 13:00:00", "1.27601", "103.836"]
2: (11) ["SN78463977", "269836", "1", "1", "15", "92656072", "Customer 517", "2018-10-11 16:00:00", "2018-10-11 19:00:00", "1.31924", "103.797"]
3: (11) ["SN16822741", "559782", "1", "1", "15", "94274895", "Customer 202", "2018-10-11 12:00:00", "2018-10-11 15:00:00", "1.36392", "103.861"]
最佳答案
您的 handleClick
处理程序未绑定(bind),因此无法访问其中的 this
。您需要在构造函数中绑定(bind)它或使用箭头函数。
handleClick = () => {
console.log("success");
console.log(this.state.data);/*this is where error occur*/
}
或
constructor(props) {
super(props);
this.state = {data:[]};
this.handleClick = this.handleClick.bind(this);
}
关于javascript - 如何将csv数据分配给react中的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56126115/