如果我想检查imagesWithChangedName中是否有id与图像id相同的对象,我应该在XXX中键入什么?
const [imagesWithChangedName,setImagesWithChangedName] = useState([])
const handlePhotoNameChange = (e, imageID) =>{
e.preventDefault()
if(imageID && e.target.value){
if(XXX === imageID)
setImagesWithChangedName([...imagesWithChangedName,{id:imageID, changedName: (e.target.value) }])
}
}
}
编辑:此外,如果XXX===imageID等于true,如何将的changedName值替换为新值?
const [imagesWithChangedName,setImagesWithChangedName] = useState([])
const handlePhotoNameChange = (e, imageID) =>{
e.preventDefault()
if(imageID && e.target.value){
if(imagesWithChangedName.some(image => image.id === imageID)) {
const indexToChange = imagesWithChangedName.reduce((acc, image, i) => image.id === imageID ? i : acc, 0);
const mutableImages = [...imagesWithChangedName];
mutableImages[indexToChange] = { id:imageID, changedName: (e.target.value) };
setImagesWithChangedName(mutableImages);
}
}
}
这将找到您的图像并替换正确的值,而不向数组添加额外的值。
将if(XXX === imageID)
替换为:
if (imagesWithChangedName.find(img => img.id === imageID))
替换内容:
if(imageID && e.target.value){
const image = imagesWithChangedName.find(img => img.id === imageID);
if (image) {
image.changedName = e.target.value;
setImagesWithChangedName(imagesWithChangedName);
}
}