简体   繁体   中英

How to setState a specific value of a particular parameter in reactjs

this.state = {
  array: [1, 2, 3],
  objects: [{ id: 1 }, { id: 2 }, { id: 3 }]
}

How can I change the specific value of an object or array in the state without setStating the whole array/object?

something like

this.setState({ array[2]: 5 })
this.setState({ object[0].id: 0 })

You could use a helper function to set an element at an index and return that newly updated array

 const array = [1, 2, 3] const object = [{id: 1}, {id: 2}, {id: 3}] const setElementAtIndex = (index, value, array) => [...array.slice(0, index), value, ...array.slice(index + 1) ] console.log(setElementAtIndex(0, 99, array)) console.log(setElementAtIndex(1, 99, array)) console.log(setElementAtIndex(2, 99, array)) console.log(setElementAtIndex(0, {...object[0], id: 0 }, object))

this.setState({ array: setElementAtIndex(2, 5, array) })
this.setState({ object: setElementAtIndex(0, { ...object[0], id: 0 }, object) })

I would use map .

 const state = { array: [1,2,3], objects: [{id: 1}, {id: 2}, {id: 3}] } const newArray = state.array.map((v, i) => i === 2? 5: v); const newObjects = state.objects.map((v, i) => i === 0? {...v, id: 0}: v); console.log(newArray); console.log(newObjects); // this.setState({...this.state, array: newArray }); // this.setState({...this.state, objects: newObjects });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM