【问题标题】:Removing a file from an array of files on click with react.js使用 react.js 从文件数组中删除文件
【发布时间】:2020-07-07 15:53:10
【问题描述】:

我正在尝试创建一个函数,该函数允许我使用索引 onclick 从文件数组中删除文件。

**input:** files to upload stored in the state using hooks

**output:** files to upload stored in the state minus the removed file

这是我到目前为止所拥有的,我想知道我是否走在正确的轨道上,或者有更好的方法来做这件事。

// remove document from uploadFiles array
      const removeFile = index => {
        // take an array of files and select a file at a given index
        // remove a file at a selected index
        // reassign all the indexs
        const selectFile = index;
        setFilesToUpload(filesToUpload.filter(file => file.selectFile[index] !== selectFile));
      };

      return (
        <div className={uploadStyles.fileContainer} key={uuid()}>
          <div className={uploadStyles.fileTitle}>
            <p>Document {(index += 1)}</p>
            <SquareButton
              label={"remove file"}
              icon={"x-mark"}
              small={true}
              name={file.selectFile}
              onClick={() => removeFile(index)}
            />
          </div>
          <p className={uploadStyles.filePath}>{file.path}</p>
          <p className={uploadStyles.fileTS}>
            {file.type}
            {"   "}|{"   "}
            {formatBytes()}
          </p>
          <div className={uploadStyles.progressLine} />
        </div>
      );
    });
  };

【问题讨论】:

    标签: javascript arrays reactjs state


    【解决方案1】:

    我相信你可以使用splice。

    之前:

    setFilesToUpload(filesToUpload.filter(file =&gt; file.selectFile[index] !== selectFile));

    之后:

    setFilesToUpload(filesToUpload.splice(index, 1)));

    第二个参数表示要删除的元素数量

    Splice

    splice() 方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容

    【讨论】:

    • 告诉我进展如何:)
    • 它可以工作,但是如果我尝试从数组中删除 1 个文件(如果有多个文件),它也会删除该文件的每个索引
    【解决方案2】:

    filter方法中的第二个参数是index,利用它来简化。

    const removeFile = (index) => {
      setFilesToUpload(filesToUpload.filter((_, i) => i !== index));
    };
    

    【讨论】:

    • 这个解决方案有效但是我如何处理这只是我需要过滤掉的数组中的一项的情况。
    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多