在完全完成查询之前下载excel文件

时间:2019-01-26 13:42:40

标签: reactjs export-to-excel

我曾经使用过图书馆react-data-export

我的问题是我在完成查询之前创建了excel文件,现在我必须按两次才能使其工作

代码:

import ReactExport from "react-data-export";
const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
import axios from 'axios';

class Main extends Component {
    constructor() {
        super();
        this.state = {
            multiDataSet: []
        }
        this.getDataExcel = this.getDataExcel.bind(this);
    }

getDataExcel() {
    let self = this;
    axios.get('/app/webapi/datos/excel'
        ).then(function (response) {
            self.setState({ multiDataSet: response.data});
        })
        .catch(function (error) {
            console.log(error);
        });
}   
render() {
    return (
        <ExcelFile name="excel2" filename="excelDatos" element={<Button label="Exportar" icon="fa fa-file-excel-o" onClick={this.getDataExcel}/>}>
            <ExcelSheet dataSet={this.state.multiDataSet} name="Datos_Excel"/>
        </ExcelFile>

    );
)

如何等待查询完成以创建Excel?

1 个答案:

答案 0 :(得分:1)

您可以开始在组件安装上获取数据(单击下载按钮之前),并且仅在获取数据后才呈现ExcelFile。像这样:

class Main extends Component {
    constructor() {
        super();
        this.state = {
            fetching: true,
            multiDataSet: null,
        }
        this.getDataExcel = this.getDataExcel.bind(this);
    }

    componentDidMount() {
        // ********* the data is fetched on component mount, before the download button appears *********
        this.getDataExcel();
    }

    getDataExcel() {
        let self = this;
        axios.get('/app/webapi/datos/excel'
            ).then(function (response) {
                self.setState({ multiDataSet: response.data, fetching: false });
            })
            .catch(function (error) {
                console.log(error);
                self.setState({ fetching: false });
            });
    }   

    render() {
        const { fetching, multiDataSet } = this.state;
        if (fetching) return <div>Loading...</div>;
        if (!multiDataSet) return <div>Failed to fetch data</div>;

        return (
            // ********* notice I removed the onClick event from the button *********
            <ExcelFile name="excel2" filename="excelDatos" element={<Button label="Exportar" icon="fa fa-file-excel-o"/>}>
                <ExcelSheet dataSet={this.state.multiDataSet} name="Datos_Excel"/>
            </ExcelFile>
        );
    }
}