如何制作可以解决表问题的深层副本

问题描述 投票:0回答:2

我使用表材质表,在其中设置一个新元素到我的对象,称为tableData。因此,该功能会为我的代码和API带来问题,因为我使用Patch进行更新。我实现了我的对象的传统和自定义深层副本,以避免表将此元素添加到我的对象。

但由于某种原因它不起作用。这是该表的一个示例,您可以在其中查看它如何将tableData添加到示例对象。 https://codesandbox.io/s/lx2v9pn91m请检查控制台

上面我展示了真实对象,并在元素5数组中,在每次渲染后出现tableData。额外的注释,我传递给表的表的属性是:data = {MyRealObject.element5}


This is the struct of my real object: 
MyRealObject{ 
element1: boolean, 
element2: boolean ,
element3: Array ,
element4: Array ,
Cards: Array ,
}

Card{ 
Id: number ,
CardNumber : number ,
CardFormat : {CardFormatObject},

//here where appear the tableData after each render 
} 

CardFormatObject{ 
Id: number ,
CardNumberLength : number ,
CardFormatLength : number ,
Default:boolean ,
Name: string ,
}

This is the lastest custom deep copy I did and didnt work:

deepcopy(MyRealObject:MyRealObject):MyRealObject{

let salvaCard=[]
for(let i=0;i<user.Cards.length;i++){
   salvaCard[i]=this.deepCardCopy(MyRealObject.Cards[i])
}
return{
      element1: MyRealObject.element1,
      element2: MyRealObject.element2, 
      element3: [...MyRealObject.element3], //I know here is not deep but isnt important now, and it isnt affected
      element4: [...MyRealObject.element4],

      Cards: salvaCard,


}as MyRealObject
}

public deepCardCopy(card:Card):Card{
    return {
      Id:card.Id,
      CardNumber:card.CardNumber,
      CardFormat:{...card.CardFormat}
    } as Card;
  }


//////////////////////////////

This are others deep code that I used and dont works, I share to save you time:
--------old solution 1(i dont like it, you can lose element if there are null)------------------------------------------------


// Cards: JSON.parse(JSON.stringify(MyRealObject.Cards)),

---------old solution 2-------------------------------------------

      // MyRealObject.Cards.map(card=>{
      //   const {tableData,...record}=card
      //   return record
      // }),
javascript reactjs material-ui deep-copy
2个回答
0
投票

setState是一个异步函数。这意味着您在调用后无法立即看到结果。你必须等待setState完成。在callback中有一个setState参数,你可以用它来得到this.state的结果

handleSelectedID = rowData => {
    const selectedID = rowData.map(item => item.id);
    this.setState({ selectedID }, () => {
      // setState is async
      // this is the callback
      console.log(this.state.selectedID);
    });
};

我稍微改变了你的示例代码,给你一个例子:https://codesandbox.io/s/1olz33pmlj


0
投票

我找到了一个解决方案,它是在我将对象传递给表的那一刻传递克隆,例如:

data = {MyRealObject.map(x => Object.assign({},x))}

问题是,创建表的人没有对数据进行克隆,使用相同的引用,因此最好这样做以避免组件中的某些人没有克隆对象的问题。

请注意,DONT使用这种方式data = {... MyRealObject}或data = {Object.assign({},MyRealObject)}

CORRECT是:data = {MyRealObject.map(x => Object.assign({},x))}

两个表达看起来相似,但它们不一样。

© www.soinside.com 2019 - 2024. All rights reserved.