ReactJS updating a single object inside a state array

前端 未结 4 1138
遥遥无期
遥遥无期 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:01

    In my opinion with react state, only store things that's really related to "state", such as things turn on, off, but of course there are exceptions.

    If I were you I would pull away the array of devices as a variable and set things there, so there is what I might do:

    var devices = [];
    
    var MyComponent = React.createClass({
        ...
        updateSomething: function (device) {
    
            var index = devices.map(function(d){
                return d.id;
            }).indexOf(device.id);
    
            if (index !== -1) {
               // do some stuff with device
               devices[index] = device;
    
               if(NeedtoRender) {
                   this.setState({devices:devices});
               }
            }
        }
    });
    

提交回复
热议问题