【发布时间】:2021-01-14 01:26:16
【问题描述】:
我正在尝试使用 react 构建一个 csv 文件上传器。选择文件并尝试使用它设置状态时,我收到“传播不可迭代实例的无效尝试”错误。这是我给出该错误的代码:
const IFImport = (props) => {
const [file, setFile] = useState(null);
const [loading, setLoading] = useState(false);
const onUpload = async (e) => {
const csvFile = e;
console.log(csvFile)
setFile(...file, csvFile)
}
return (
<>
<ContentRow>
<h1>
<Link to={"/"}>
<Button color="link"><</Button>
</Link>
Upload Enrollment Information
<ErrorList error={props.error} />
</h1>
</ContentRow>
<ContentRow>
<Label>Upload a CSV File for Enrollment</Label>
<FormGroup>
<div>
{file !== null ? <p>{file.name}</p> : ""}
</div>
<div>
<Input
type="file"
name="data.file"
multiple={false}
onChange={e => onUpload(e)}
accept="/csv"
/>{" "}
</div>
</FormGroup>
</ContentRow>
</>
);
};
export default IFImport;
我认为这是在此 onUpload 函数中设置状态的问题,因此我尝试在此处不设置状态,但随后出现合成偶数错误。谁能告诉我处理这种上传的最佳方式?
【问题讨论】:
-
...file是我认为的错误所在。您使用null初始化它的事实可能是原因。null不可传播用{}(或[],取决于你的file的样子)初始化它 -
感谢您的回复!使用
[ ]初始化文件给了我上面提到的合成事件问题。因此,console.log 不是返回我选择的文件,而是返回一个合成的偶数。
标签: javascript reactjs input file-upload jsx