javascript - 使用 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>
);
});
};
解决方案
在过滤器方法中,第二个参数是index
,利用它来简化。
const removeFile = (index) => {
setFilesToUpload(filesToUpload.filter((_, i) => i !== index));
};
推荐阅读
- laravel - Laravel,两个 api PUT 动作,一个有效,另一个无效
- textures - 如何在我的代码中添加具有 shapefactory 形状(立方体)的自定义纹理?
- c++ - 为在与类方法中的类相同的命名空间中定义的结构调用重载运算符
- lua - REPL 和脚本之间的 Lua 语法规则有何不同?
- javascript - 在 Koa 中,中间件中的 await next()、return await next()、return next()、next() 有什么区别?
- html - 使用 v-if 根据变量的值显示 html 元素
- regex - IIS Url Rewriter:重定向语言代码
- node.js - 如何在 node.js 中处理 mongoDB 常规操作
- reactjs - 无效的挂钩呼叫。反应
- spring-boot - 对象未存储在 Redis 缓存中