问题描述
我正在通过从数据库获取数据来将图像显示为芯片。如何删除db显示的图像芯片?
{user.isImageUploaded != null ?
<div >
<p>
{user.isImageUploaded.map(item => {
const datatypeVar = item.fileType;
const dataimageCode = item.filedata;
const dataname = item.fileName
return (
<Chip
label="Basic"
size="small"
label={dataname}
onDelete={() => this.handleImgDelete(dataname)}
avatar={
<Avatar variant="rounded" alt="Remy Sharp" src=
{`data:${datatypeVar};base64,${dataimageCode}`} />
}/>
)
})} : null}
user.isImageUploaded是从数据库映射的数据。如何编写handleImgDelete?
解决方法
首先,我们需要从数组中删除值的索引,这可以通过使用.map函数的第二个参数来实现。
.map((item,index) => { do some stuff here })
项目将是实际图像,索引将是数组中当前图像的索引(他们会猜到XD)
因此,您无需给dataeName赋予handeImgDelete,而是给索引
{user.isImageUploaded != null ?
<div >
<p>
{user.isImageUploaded.map((item,index) => {
const datatypeVar = item.fileType;
const dataimageCode = item.filedata;
const dataName = item.fileName
return (
<Chip
label="Basic"
size="small"
label={dataName}
onDelete={() => this.handleImgDelete(index)}
avatar={
<Avatar variant="rounded" alt="Remy Sharp" src=
{`data:${datatypeVar};base64,${dataimageCode}`} />
}/>
)
})} : null}
您的handleImgDelete可能是这样的:
const handleImageDelete(index) => {
// I am aware that this is a bad way of deep cloning a object (if you encounter problems with this you could use https://lodash.com/docs/#cloneDeep)
let userCopy = JSON.parse(JSON.stringify(user));
userCopy.isImageUploaded.splice(index,1)
// Do stuff here to send to the db
}