React CSV Downloader正在下载一个空的CSV文件

icnyk63a  于 2023-10-13  发布在  React
关注(0)|答案(1)|浏览(129)

我有一个React CSV Downloader插件的问题,如下所示:

export default function Component(props) {
    ...
    [data, setData] = useState([]);
    ...

    const downloadData = async () => {
        return new Promise(async (resolve, reject) => {
      
        // make request via axios
        return data;

        try{
            ...
            // do some logic to clean the data
            ...

            setData(cleanedData);
            resolve(data); // also tried resolve(cleanedData);
          } catch (error) {
            console.log(error);
            reject(error);
          }
        });
      };

      return (
        <CsvDownload
          datas={downloadData}
          filename={"name"}
          extension=".csv"
          handleEmpty={() => void 0}
        >
            <Button>Download</Button>
        </CsvDownload>
    );
}

问题是,当下载CSV时,第一次下载文件时它是空的。第二次单击下载按钮后,CSV将被填充。有谁能帮我解释一下这里发生了什么吗?
谢谢.

s4n0splo

s4n0splo1#

别担心把它更新到下面。使用useEffect & useRef仅在useEffect具有可供下载的数据之后,在清除数据之前,触发CSVDownloader的Click()函数。

export default function Component(props) {
    ...
    const [data, setData] = useState([]);
    const csvInstance = useRef(null);
    ...

    const downloadData = async () => {
      
        try{
            // make request via axios
                return data;
            ...
            // do some logic to clean the data
                return cleanedData
            ...

            setData(cleanedData);

        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        if (
            !!data &&
            data.length > 0 &&
            csvInstance &&
            csvInstance.current &&
            csvInstance.current.handleClick
        ) {
            setTimeout(() => {
                csvInstance.current.handleClick();
                setData([]); // reset data after download
            });
        }
    }, [data]);

    return (
        <CsvDownload
          datas={data}
          filename={"name"}
          extension=".csv"
          handleEmpty={() => void 0}
          ref={csvInstance}
        >
            <Button onClick={downloadData}>Download</Button>
        </CsvDownload>
    );
}

希望这能帮助到某人。

相关问题