我有一个简单的反应组件,让用户上传csv文件使用react -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数据分配给state。
这是控制台打印成功的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"]发布于 2019-05-14 16:35:30
您的handleClick处理程序未绑定,因此在其中访问this将不起作用。您要么需要在构造函数中绑定它,要么使用箭头函数。
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);
}发布于 2019-05-14 16:34:44
看起来handleClick没有绑定,因此this在其中是未定义的。请改用:
handleClick = () => {
console.log("success");
console.log(this.state.data);/*this is where error occur*/
}发布于 2019-05-14 16:42:50
正如他们已经说过的,你的handleClick没有绑定到this,所以要解决这个问题,你需要通过改变你的点击来绑定它
<button onClick={this.handleClick.bind(this)}>
Upload
</button>或者像其他人提到的那样,让你的函数成为一个箭头函数
handleClick = () => {
console.log("success");
console.log(this.state.data);/*this is where error occur*/
}或者我最不喜欢的方式,绑在consructor里。
constructor(props) {
super(props);
this.state = {data:[]};
this.handleClick = this.handleClick.bind(this);
}https://stackoverflow.com/questions/56126115
复制相似问题