TypeError:散布不可迭代实例和合成事件的尝试无效

时间:2020-09-28 12:53:03

标签: javascript reactjs input file-upload jsx

我正在尝试使用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">&lt;</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函数中设置状态的问题,因此我尝试不在此处设置状态,但随后我得到了一个综合的甚至错误。谁能告诉我处理这种上载的最佳方法吗?

1 个答案:

答案 0 :(得分:1)

首先,您尝试传播显然会失败的null值(这是file状态下的初始值)。

其次-e不是您要查找的文件,而是Event对象。如果要获取上传的文件,请使用

const csvFile = e.target.files;

而是将用户上传的每个文件作为数组保存。