简体   繁体   中英

Cannot send an array-type variable from React.js front-end to Django backend

I need to send an array from React.js frontend to the Django backend. I can easily send all variables, except just an array csvData .

I see that console.log("csvData", csvData) returns the following data:

NUM,COL1,COL2
1,300,500
2,566,VL

This is the code of React component called BatchFlights :

import React, { Component, Fragment } from 'react';
import TopControls from "./layout/batch/TopControls"
import MainContent from "./layout/batch/MainContent"
import BottomControls from "./layout/batch/BottomControls"
import styles from "./layout/styles/styles";
import { withStyles } from "@material-ui/core/styles";


class BatchFlights extends Component {

  constructor(props) {
      super(props);
      this.state = {
          csvData: [],
          temperature: 20,
          visibility: 5999.66,
          windIntensity: 8.0,
          prediction: 0,
          labelWidth: 0
      };
      this.handleChange = this.handleChange.bind(this);
  };

  componentDidMount() {
      this.fetchData();
  };

  updateDelay(prediction) {
    this.setState(prevState => ({
      prediction: prediction
    }));
  };

  setCsvData = csvData => {
    this.setState({
      csvData
    }, () => {
      console.log("csvData",this.state.csvData)
    });
  }

  fetchData = () => {
      const url = "http://localhost:8000/predict?"+
        '&temperature='+this.state.temperature+
        '&visibility='+this.state.visibility+
        '&windIntensity='+this.state.windIntensity+
        '&csvData='+this.state.csvData;

      fetch(url, {
        method: "GET",
        dataType: "JSON",
        headers: {
          "Content-Type": "application/json; charset=utf-8",
        }
      })
      .then((resp) => {
        return resp.json()
      })
      .then((data) => {
        this.updateDelay(data.prediction)
      })
      .catch((error) => {
        console.log(error, "catch the hoop")
      })
  };

  handleChange = (name, event) => {
    this.setState({
      [name]: event.target.value
    }, () => {
      console.log("csvData", csvData)
    });
  };


  handleReset = () => {
      this.setState({
          prediction: 0
      });
  };

  render() {
    return (

        <Fragment>

            <TopControls state={this.state} styles={this.props.classes} handleChange={this.handleChange} />

            <MainContent state={this.state} styles={this.props.classes} setCsvData={this.setCsvData} />

            <BottomControls state={this.state} styles={this.props.classes} fetchData={this.fetchData} handleReset={this.handleReset}/>

        </Fragment>

    );
  }
}

const StyledBatchFlights = withStyles(styles)(BatchFlights);
export default StyledBatchFlights;

MainContent

import React, { Component, Fragment } from 'react';
import CssBaseline from '@material-ui/core/CssBaseline';
import CSVDataTable from './CSVDataTable';

class MainContent extends Component {
    render() {
        return (
          <Fragment>
              <CssBaseline />
              <main className={this.props.styles.mainPart}>
                  <CSVDataTable setCsvData={this.props.setCsvData} />
              </main>
          </Fragment>
        );
    }
}

export default MainContent;

CSVDataTable

import React, { Component } from 'react';
import { CsvToHtmlTable } from 'react-csv-to-table';
import ReactFileReader from 'react-file-reader';
import Button from '@material-ui/core/Button';

const sampleData = `
NUM,COL1,COL2
1,300,500
2,566,VL
`;

class CSVDataTable extends Component {

    state={
      csvData: sampleData
    };

    handleFiles = files => {
        var reader = new FileReader();
        reader.onload =  (e) => {
          // Use reader.result
          this.setState({
            csvData: reader.result
          })
          this.props.setCsvData(reader.result)
        }
        reader.readAsText(files[0]);
    }

    render() {
        return <div>
          <ReactFileReader
            multipleFiles={false}
            fileTypes={[".csv"]}
            handleFiles={this.handleFiles}>
            <Button
                variant="contained"
                color="primary"
            >
                Load data
            </Button>

          </ReactFileReader>
          <CsvToHtmlTable
            data={this.state.csvData || sampleData}
            csvDelimiter=","
            tableClassName="table table-striped table-hover"
          />
    </div>
    }
}

export default CSVDataTable;

But when csvData arrives to Django backend, it's empty:

csvData = request.GET.get('csvData')

print("CSV DATA",csvData)  # IT IS EMPTY!!!

I believe the problem is you're trying to coerce the array csvData into a string and attach the stringified array as a parameter to your get request fetchData

'&csvData='+this.state.csvData;

If the value of csvData is made up of arrays within an array, when you coerce the array into a string through you get:

'' + [[], [], []]  // "[object Object]" 

If you want to keep your current get function you should instead do

'&csvData='+JSON.stringify(this.state.csvData);

but it is highly recommended that you change the get request a post or put request if you are dealing with highly nested JSON objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM