簡體   English   中英

React - 拼接從狀態數組中刪除太多元素

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

我正在嘗試創建一個具有可變數量輸入的圖片庫。 我已經成功創建了一個添加按鈕,它將向處於該狀態的數組添加一個新元素。 但是,當我單擊按鈕從數組中刪除一個元素時,它會刪除除第一個元素之外的所有元素。 有人可以幫我弄清楚我哪里出錯了嗎?

我在父組件中的初始化/添加/刪除邏輯:

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

    )
}

Splice 直接對數組進行變異,這在 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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM