我正在为图像上传器实现删除功能。我的错误消息是Cannot read property 'id' of undefined
。我认为我没有正确分配ID,而我的方法对手头的任务是错误的。
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
我希望文件从阵列中删除。实际结果是什么也没有发生,并且出现错误消息。
答案 0 :(得分:1)
deleteImage = (file_id) => {
const { files } = this.state;
this.setState({
files: files.filter(file => file.id !== file_id),
});
}
在将文件ID传递到 deleteImage 函数时,应编写此代码。
答案 1 :(得分:1)
您可以删除具有索引值的对象
deleteImage = (file, index) => {
const myNewFiles = [...this.state.files]; // copy of Original State
myNewFiles.splice(index, 1);
this.setState({
files: myNewFiles
});
};
我也做了一个沙盒示例