Replace array entry with spread syntax in one line of code?

前端 未结 6 776
情深已故
情深已故 2021-02-04 00:02

I\'m replacing an item in a react state array by using the ... spread syntax. This works:

let newImages = [...this.state.images]
newImages[4] = updatedImage
this         


        
6条回答
  •  野性不改
    2021-02-04 01:01

    I refer to @Bardia Rastin solution, and I found that the solution has a mistake at the index value (it replaces item at index 3 but not 4).

    If you want to replace the item which has index value, index, the answer should be

    this.setState({images: [...this.state.images.slice(0, index), updatedImage, ...this.state.images.slice(index + 1)]})
    

    this.state.images.slice(0, index) is a new array has items start from 0 to index - 1 (index is not included)

    this.state.images.slice(index) is a new array has items starts from index and afterwards.

    To correctly replace item at index 4, answer should be:

    this.setState({images: [...this.state.images.slice(0, 4), updatedImage, ...this.state.images.slice(5)]})
    

提交回复
热议问题