【发布时间】:2020-11-08 02:02:48
【问题描述】:
一个用例是:
- 用户删除文件
- 获取文件并使用
exceljs读取 - 从列中获取值并将其保存在数组中
ids - 使用
ids的内容设置状态变量onDropIds。我得到了步骤1-3工作。我无法让4工作。
请参阅:状态始终打印为空,即使集合包含值。请参见代码行 41-43。
import React, { useState, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import Excel from "exceljs";
export default function Test(props) {
// Local state
const [onDropIds, setOnDropIds] = useState(new Set());
// Callback fires as soon as the file is dropped
const onDrop = useCallback((acceptedFiles) => {
const file = acceptedFiles[0];
const reader = new FileReader(); // reads the file using the `FileReader` API
reader.onabort = () =>
console.warn(`Reading of file ${file.path} was aborted.`);
reader.onerror = () =>
console.error(`Reading of file ${file.path} has failed.`);
reader.onloadend = (e) => {
const bufferArray = reader.result;
// temporarily hold a set of values
const ids = new Set();
const workbook = new Excel.Workbook();
workbook.xlsx
.load(bufferArray)
.then((sheet) => {
workbook.worksheets[0].eachRow({ includeEmpty: true }, (row) => {
const colValue1 = (row.values[1] || "").trim().toUpperCase();
if (colValue1 && colValue1 !== "HEADERNAME") {
ids.add(colValue1);
}
});
})
.then(() => {
// set it to the state
setOnDropIds(ids);
// debug: print results
console.log(onDropIds);
console.log("---");
console.log(ids);
});
};
reader.readAsArrayBuffer(file);
}, []);
// Initialize the dropzone hook
const { getRootProps, getInputProps, open, acceptedFiles } = useDropzone({
noClick: true,
noKeyboard: true,
multiple: false,
onDrop,
});
return (
<div>
<div
{...getRootProps()}
style={
acceptedFiles && acceptedFiles.length
? {
textAlign: "center",
border: "1px solid #198562",
marginTop: "0.5em",
backgroundColor: "#d9fff3",
}
: {
textAlign: "center",
border: "1px dashed #000",
marginTop: "0.5em",
}
}
>
<input {...getInputProps()} />
<button
style={{ marginTop: "0.5em" }}
color={acceptedFiles && acceptedFiles.length ? "#00ff00" : "#ff0000"}
onClick={open}
>
Browse
</button>
{acceptedFiles && acceptedFiles.length ? (
<span>
{acceptedFiles[0].path}{" "}
<i className="fas fa-check-circle" style={{ color: "#75B436" }}></i>
</span>
) : (
"Drag 'n' drop a file here..."
)}
</div>
</div>
);
}
【问题讨论】:
-
我已经用正确的解决方案添加了一个指向我的答案的链接。您可以根据您的要求对其进行检查
标签: reactjs callback react-hooks exceljs react-dropzone