我正在为图像 uploader 实现删除功能。我的错误消息是无法读取未定义的属性“id”
。我认为我没有正确分配 id,并且我的方法对于手头的任务是错误的。
- 尝试将对象传递到函数中并使用 JavaScript 删除 API 来删除特定文件。直接改变状态不是最佳实践,而是复制状态,修改然后粘贴新状态。
- 尝试使用名称作为标识符,但不起作用。建议通过id或者key删除。
import * as React from "react"
import Dropzone, { DropFilesEventHandler } from "react-dropzone"
import FaIcon from "components/FaIcon"
import { PrimaryButton } from "components/Buttons"
interface ImageFile extends File {
preview?: string
id: any
}
class ImageUpload extends React.Component {
state = {
files: []
}
onDrop: DropFilesEventHandler = (files: ImageFile[]) => {
files.map(file => Object.assign(file, {
preview: URL.createObjectURL(file)
}))
this.setState({ files: [...this.state.files, ...files] })
}
deleteImage = (file: ImageFile, index: number) => {
console.log(file, index)
// this.setState({
// files: this.state.files.filter(file => file.name !== file),
// });
}
render() {
const files = this.state.files.map((file: ImageFile, index: number) => (
console.log(file),
(
<div key={index}>
<div>
<img src={file.preview} />
<div onClick={() => this.deleteImage(file, index)}>
<FaIcon icon="plus" />
</div>
</div>
</div>
)
))
return (
<div>
<div>
<h2>Upload Images</h2>
</div>
<form>
<div>
{files}
<Dropzone onDrop={this.onDrop} accept="image/*">
<FaIcon icon="plus"/>
</Dropzone>
</div>
<div>
<label>Category</label>
<div>
<input
type="text"
placeholder={"please enter / select..."}
value={this.state.categoryInput}
onChange={(e) => this.categoryInputValue(e)}
/>
</div>
<PrimaryButton>Upload</PrimaryButton>
</div>
</form>
</div >
)
}
}
export default ImageUpload
我希望该文件从数组中删除。实际结果是没有任何反应,并且出现错误消息。
最佳答案
您可以删除具有索引值的对象
deleteImage = (file, index) => {
const myNewFiles = [...this.state.files]; // copy of Original State
myNewFiles.splice(index, 1);
this.setState({
files: myNewFiles
});
};
我还制作了一个沙箱示例
关于javascript - 从状态数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55902222/