将推送数据反应到数组对象中

时间:2019-06-08 18:13:20

标签: arrays reactjs object import-from-excel

如何从importFile.js导入数据到dataTable.js?

https://github.com/Romson/CSV-file-uploader/blob/master/src/components/importFile.js https://github.com/Romson/CSV-file-uploader/blob/master/src/components/dataTable.js

尝试使用此功能将导入数据中的嵌套数组从importFile.js更改为数组对象。

const newArray = [data].map(
  ([firstName, lastName, issueCount, dateOfBirth]) => ({
    firstName,
    lastName,
    issueCount,
    dateOfBirth
  })
);

然后使用以下命令将其推入dataTable.js:

data.rows.push(newArray);

在React中执行此操作的正确方法是什么?

预期结果是使导入的数据显示在此表中:

https://csv-file-uploader.herokuapp.com/

1 个答案:

答案 0 :(得分:0)

您想要做的是使DataTable组件成为Reader组件的子组件。您需要Reader组件中的对象数组作为DataTable组件中datatable的rows属性。正如您所说的,您是个初学者,因此最好从react钩子开始,这很容易。

阅读器组件

import React, {useState} from "react";
import CSVReader from "react-csv-reader";
import DatatablePage from "./dataTable";
import "../index.css";

const Reader = () =>  { 
 const [data, setData] = useState([]);
return (
  <div className="container">
    <CSVReader
      cssClass="react-csv-input"
      label="Upload a new CSV file"
      onFileLoaded={(data) => setData(data)}
    />
    <DatatablePage uploadedData={data} />
  </div>
);
}

export default Reader;

DatatablePage组件

import React from "react";
import { MDBDataTable } from "mdbreact";

const DatatablePage = ({uploadedData}) => {
  const data = {
    columns: [
      {
        label: "First Name",
        field: "name",
        sort: "asc",
        width: 150
      },
      {
        label: "Last Name",
        field: "surname",
        sort: "asc",
        width: 270
      },
      {
        label: "Issue count",
        field: "issuecount",
        sort: "asc",
        width: 200
      },
      {
        label: "Date of birth",
        field: "dateofbirth",
        sort: "asc",
        width: 100
      }
    ],
    rows: []
  };
// we append the passed props in the rows. read about spread operator if unaware of it.

const datatableProps = {...data, rows: uploadedData}; 
  return <MDBDataTable striped bordered hover uploadedData={uploadedData} data={datatableProps} />;
};

export default DatatablePage;

我们正在使用react hooks创建一个名为data的状态变量及其设置器。然后,将此状态变量传递给可以呈现它的子组件。