简体   繁体   English

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

[英]React - Splice removing too many elements from state array

I'm trying to create an image gallery that has a variable number of inputs.我正在尝试创建一个具有可变数量输入的图片库。 I have successfully created an add button which will add a new element to my array that is in the state.我已经成功创建了一个添加按钮,它将向处于该状态的数组添加一个新元素。 However, when I click the button to remove an element from the array, it removes all elements except the first one.但是,当我单击按钮从数组中删除一个元素时,它会删除除第一个元素之外的所有元素。 Could someone help me figure out where I'm going wrong here?有人可以帮我弄清楚我哪里出错了吗?

My initialization/add/remove logic in parent component:我在父组件中的初始化/添加/删除逻辑:

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))
}

My image gallery component:我的图片库组件:

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>
            )
        })

    )
}

Splice mutates the array directly, which is generally disapproved in React. Splice 直接对数组进行变异,这在 React 中一般是不被认可的。

While the recommended approach is using the filter method to remove, you can do it in this way if u want to use splice -虽然推荐的方法是使用过滤器方法来删除,但如果您想使用拼接,您可以通过这种方式进行 -

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM