首页 > 解决方案 > 在 React 中按值复制道具

问题描述

我正在使用 TypeScript 开发 reactJS 应用程序。我创建了一个类:

export class A{
  showLegend: boolean = true;
  showToolTip:boolean = true;
  showDataLabel:boolean = false;
  legendText: string = "Smith-Chart";
  showAnimation:boolean = false;
  legendPosition:string = "Bottom";
  showMarker:boolean = true;
  showMarkerLines:boolean = true;
  linesColor:string = "";
  markerColor:string = "";
  markerBorderColor:string = "";
  markerBorderWidth:number = 2;
}

我的道具有这个类的两个对象:

let localCopy : A[]
constructor(props: any){
  super(props);
  localCopy = this.props.slice;
}

这确实将数据复制到localCopy数组中,但是当我更新时localCopy,实际的道具也会更新。

我怎样才能复制道具我的价值而不是通过引用?

标签: reactjstypescript

解决方案


你可以通过这种方式不可变地复制

localCopy = {...this.props};

ES5 中的等价物是

localCopy = Object.assign({}, this.props);

推荐阅读