React-拼接从状态数组中删除了太多元素



我正在尝试创建一个具有可变数量输入的图像库。我已经成功创建了一个添加按钮,它将向处于状态的数组添加一个新元素。但是,当我单击按钮从数组中删除一个元素时,它会删除除第一个元素之外的所有元素。有人能帮我弄清楚哪里出了问题吗?

我在父组件中的初始化/添加/删除逻辑:

const newImage = {
fileName: 'placeholder.png',
description: '',
}
const [galleryImages, setGalleryImages] = useState([newImage])
const addNewImage = () => {
setGalleryImages(galleryImages.concat(newImage))
}
const removeImage = (index) => {
setGalleryImages(galleryImages.splice(index, 1))
}

我的图片库组件:

const ImageGallery = ({galleryImages, setGalleryImages, addNewImage, removeImage}) => {
console.log('gallery images:', galleryImages)

return(
galleryImages.map((image, index) => {
const fileId = 'image' + (index + 1) + 'File'
const descriptionId = 'image' + (index + 1) + 'Description'

return(
<Card key={index} style={{marginTop: '10px'}}>
<Card.Body>
<div style={{position: 'absolute', top:'5px', right:'5px'}}>
<IconButton aria-label="remove" color="secondary" onClick={() => removeImage(index)}>
<CancelIcon />
</IconButton>
</div>
<Card.Title>Image {index+1}</Card.Title>
<Form.Group>
<Form.File id={fileId} />

<Form.Label>Image Description</Form.Label>
<Form.Control id={descriptionId} type="text" placeholder="Image description..."/>
</Form.Group>
</Card.Body>
{ index === (galleryImages.length - 1) &&
<div style={{left: '0px', right:'0px', flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center', bottom: '-30px', position: 'absolute'}}>
<IconButton aria-label="add another image" onClick={() => addNewImage()}>
<AddCircleIcon style={{color: 'green', fontSize: 40, backgroundColor: 'white', borderRadius: '50%'}}/>
</IconButton>
</div>
}
</Card>
)
})
)
}

拼接直接突变数组,这在React中通常是不赞成的。

虽然推荐的方法是使用过滤方法来删除,但如果你想使用拼接-,你可以用这种方法

const removeImage = (index) => {
//create a new array here with the spread operator of the original array. 
//Without this, react won't recognize the change and the child component won't be re-rendered!
const galleryImagesData = [...galleryImages];
galleryImagesData.splice(index, 1)
setGalleryImages(galleryImagesData)
}

最新更新