ReactJS updating a single object inside a state array

前端 未结 4 1173
遥遥无期
遥遥无期 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: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}
    }); 
    

提交回复
热议问题