Better / faster way to change the state of a React array than cloning?

Whenever a React class has a state object that contains or contains an array, updating that state seems awkward. I usually do

var newArrayThing = _.clone(this.state.arrayThing); //or slice()
newArrayThing[123] = 42; //update stuff
this.setState({arrayThing: newArrayThing});

      

Is there a better or more elegant way to handle this? Moreover, I always feel that it is unnecessarily slow if the array is large and the change is small. All this is copying for simple change. But the state should not be edited itself, it seems, is a mantra.

Immunity assistants are mentioned in the Facebook docs, but they seem even more contrived than that.

+3


source to share


1 answer


This is a very idiomatic way to do it, but if you have problems cloning large arrays you should definitely look into the update helper you mentioned, it's not too bad:



this.setState({
  arrayThing: React.addons.update(this.state.arrayThing, {123: {$set: 42}})
})

      

+5


source







All Articles