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.setState({images:newImages})
Would it be possible to do this in one line of code? Something like this? (this doesn't work obviously...)
this.setState({images: [...this.state.images, [4]:updatedImage})
Here is my self explaning non-one-liner
You can use map:
use Array.slice
You can convert the array to objects (the
...array1
), replace the item (the[1]:"seven"
), then convert it back to an array (Object.values
) :Object.assign
does the job:...but involves a temporary object (the one at the end). Still, just the one temp object... If you do this with
slice
and spreading out arrays, it involve several more temporary objects (the two arrays fromslice
, the iterators for them, the result objects created by calling the iterator'snext
function [inside the...
handle], etc.).It works because normal JS arrays aren't really arrays1 (this is subject to optimization, of course), they're objects with some special features. Their "indexes" are actually property names meeting certain criteria2. So there, we're spreading out
this.state.images
into a new array, passing that intoObject.assign
as the target, and givingObject.assign
an object with a property named"4"
(yes, it ends up being a string but we're allowed to write it as a number) with the value we want to update.Live Example:
If the
4
can be variable, that's fine, you can use a computed property name (new in ES2015):Note the
[]
aroundn
.Live Example:
1 Disclosure: That's a post on my anemic little blog.
2 It's the second paragraph after the bullet list:
So that
Object.assign
does the same thing as your create-the-array-then-update-index-4.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.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: