簡體   English   中英

類型錯誤:傳播不可迭代實例和合成事件的嘗試無效

[英]TypeError: Invalid attempt to spread non-iterable instance and Synthetic Events

我正在嘗試使用 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 函數中設置狀態的問題,所以我嘗試不在這里設置狀態,但后來我得到了一個綜合的偶數錯誤。 誰能告訴我處理這種上傳的最佳方法?

首先,您試圖傳播顯然會失敗的null值(這是狀態file的初始值)。

其次 - e不是您要查找的文件,它是 Event 對象。 如果要獲取上傳的文件,請使用

const csvFile = e.target.files;

相反,它將把用戶上傳的每個文件保存為一個數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM