首页 > 解决方案 > 使用 react.js 从文件数组中删除文件

问题描述

我正在尝试创建一个函数,该函数允许我使用索引 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>
      );
    });
  };

标签: javascriptarraysreactjsstate

解决方案


在过滤器方法中,第二个参数是index,利用它来简化。

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

推荐阅读