javascript - How to use splice in React? -
i'm trying use splice add new components
array. if use concat
elements added @ end, need add @ beginning or in middle of array using splice
. suggest ?
class app extends react.component { state = { components: [] }; addnewelement = (element) => { this.setstate(prevstate => ({ //works fine //components: prevstate.components.concat(element) components: prevstate.components.splice(0, 0, element) })); }; }
be careful note difference between methods mutate array on called , methods returns mutated versions of array on called.
prevstate.components.splice(0, 0, element)
returns new array containing elements have been removed, purposes going nothing.
notably, splice
mutates components array; mutating state elements bad thing do; 1 simple way avoid create clone of array , splice that.
this.setstate(prevstate => { const components = prevstate.components.slice(0); components.splice(0, 0, element); return { components }; });
this functional, relatively inelegant.
other options consider use react's immutability helper or use slice
divide original array in 2 concat
bits together:
const = // index @ insert new elements const left = prevstate.components.slice(0, i) const right = prevstate.components.slice(i) return { components: left.concat(elements, right) }
Comments
Post a Comment