导出react-table会导致一次下载多个文件:React + Typescript + react-table

时间:2019-04-29 05:59:12

标签: reactjs typescript setstate react-table

我正在使用react-table,react-csv来使用react然后实现export来实现数据网格。这里的问题是文件正在多次下载。

我正在为此数据网格使用一个单独的组件,其中写入了所有导出逻辑。我只是将数据和列对象作为道具传递给该组件,然后通过导出呈现此数据网格。

我们将不胜感激

应用组件

import * as React from 'react';
import DataGrid from './RenderComponent';

export default class App extends React.Component<{},{}> {

  constructor(props:any){
   super(props);
   this.state={
                 data: getData() // This is an API call, where I get data for the react-table 
              };
  }

render()
{

   return <React.Fragment>
   <DataGrid  // the data required by react-table is passed here
       data={this.state.data}
       columns={columns} // This is column config object(for header info, also for filtering logic)
    />
   </React.Fragment>
  }
}

DataGrid组件

此组件使用react-csv和react-table渲染数据网格然后导出。但是单击“下载”后,它被下载了很多次。 我要去哪里错了?

import * as React from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import {CSVLink,CSVDownload} from "react-csv";

interface IProps 
{
    data: any;
    columns: any;
}

interface IState{
    dataToDownload : {}[] ;
}

export default class DataGrid extends React.Component<IProps,IState>  
{
    private reactTable: React.RefObject<any>;    
    private csvLink: React.RefObject<any>;

    constructor(props:any){
        super(props);
        this.state={dataToDownload : []};
        this.download = this.download.bind(this);
        this.reactTable = React.createRef();
        this.csvLink = React.createRef();
    }

    download = (event: any)=>
    {

        var currentRecords = this.reactTable.current.getResolvedState().sortedData;
        var data_to_download = [];
        for(var index = 0; index < currentRecords.length; index++) {
               let record_to_download = {};
               for (var colIndex = 0; colIndex < this.props.columns.length; colIndex++) {

                           record_to_download[this.props.columns[colIndex].Header] =
                           currentRecords[index][this.props.columns[colIndex].accessor];
                }
                data_to_download.push(record_to_download);
        }             
        this.setState({ dataToDownload :data_to_download}, ()=> {this.csvLink.current.link.click()})    
   }

    render()
    {
      return ( 
        <React.Fragment>
           <button onClick={this.download}>Download</button>
           <CSVLink
                        data={this.state.dataToDownload}
                        filename="data.csv"
                        className="hidden"
                        ref={this.csvLink}
                        target="_blank"
                        onClick={this.download}
           />

          <ReactTable>
           data={this.props.data}
           columns={this.props.columns} 
           ref={this.reactTable}
          />
        </React.Fragment>
     )
    }
}


0 个答案:

没有答案