我有一个简单的react组件,允许用户使用react-csv-reader上载csv文件,然后将其上载到数据库。如何在响应中分配csv数据到状态?从状态读取数据时遇到错误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处理程序未绑定,因此无法访问其中的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);
}

09-25 17:36
查看更多