ReactJS updating a single object inside a state array

前端 未结 4 1160
遥遥无期
遥遥无期 2021-01-04 07:13

I have a state called this.state.devices which is an array of device objects.

Say I have a function

updateSomething: functi         


        
4条回答
  •  轮回少年
    2021-01-04 08:06

    For some reason above answers didn't work for me. After many trials the below did:

    if (index !== -1) {
                let devices = this.state.devices
                let updatedDevice = {//some device}
                let updatedDevices = update(devices, {[index]: {$set: updatedDevice}})
                this.setState({devices: updatedDevices})
        }
    

    And I imported update from immutability-helper based on the note from: https://reactjs.org/docs/update.html

提交回复
热议问题