ReactJS updating a single object inside a state array

前端 未结 4 1139
遥遥无期
遥遥无期 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});
               }
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-04 08:04

    You can use the react immutability helpers.

    From the docs:

    Simple push

    var initialArray = [1, 2, 3];
    var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
    

    initialArray is still [1, 2, 3].

    So for your example you will want to do something like this:

    if (index !== -1) {
        var deviceWithMods = {}; // do your stuff here
        this.setState(update(this.state.devices, {index: {$set: deviceWithMods }}));
    }
    

    Depending on how complex your device model is you could just 'modify' the object properties in situ:

    if (index !== -1) {
        this.setState(update(this.state.devices[index], {name: {$set: 'a new device name' }}));
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-04 08:10

    I solve it doing a array splice in object I wish modify, before update component state and push of object modified again.

    Like example below:

    let urls = this.state.urls;
    
    var index = null;
    
    for (let i=0; i < urls.length; i++){
      if (objectUrl._id == urls[i]._id){
        index = i;  
      }
    }
    
    if (index !== null){
      urls.splice(index, 1);  
    }
    
    urls.push(objectUrl);
    
    this.setState((state) => {
      return {urls: urls}
    }); 
    
    0 讨论(0)
提交回复
热议问题