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

Download excel file before query in fully completed

我正在使用库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?

您可以在组件挂载时开始获取数据(在点击下载按钮之前),并在获取数据后才渲染 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>
        );
    }
}