React中如何按值而非引用复制TypeScript类实例Props
Let's break down your problem first: when you tried this.props.slice (you missed the parentheses to call the method, by the way), you only created a shallow copy of the array itself—the individual A class instances inside the array are still reference values. That’s why modifying properties on localCopy items ends up updating the original props too.
Here are a few practical solutions to create a proper value-based copy, tailored to different needs:
1. Shallow Copy (perfect for your current class structure)
Since your A class only has primitive type properties (booleans, strings, numbers), a shallow copy of each instance will work flawlessly. You can use either the spread operator or Object.assign to duplicate each object in the array:
let localCopy: A[]; constructor(props: any) { super(props); // Use spread operator to copy each instance localCopy = this.props.map(item => ({ ...item } as A)); // Alternative with Object.assign // localCopy = this.props.map(item => Object.assign({}, item) as A); }
The as A type assertion tells TypeScript that the copied object literal should be treated as an instance of A (since we’re copying all its properties over).
2. Deep Copy (for future nested reference types)
If you ever extend A to include nested objects/arrays (reference types), a shallow copy won’t cut it. For those cases, you can use JSON.parse(JSON.stringify())—just note this method won’t work if your class has functions, Symbol values, or circular references:
let localCopy: A[]; constructor(props: any) { super(props); localCopy = JSON.parse(JSON.stringify(this.props)) as A[]; }
3. Class-based Clone Method (most robust for class instances)
If you want to preserve the actual A class type (instead of copying to a plain object literal), adding a clone method to your class is the cleanest approach. This ensures you get a proper instance of A that retains all prototype methods (if you add any later):
First update your A class:
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; // Add a clone method to create a proper instance copy clone(): A { const clone = new A(); Object.assign(clone, this); return clone; } }
Then use it to copy your props array:
let localCopy: A[]; constructor(props: any) { super(props); localCopy = this.props.map(item => item.clone()); }
Quick reminder
In React, props are intended to be read-only. Modifying your local copy is totally fine, but never mutate the original props directly—it breaks React’s data flow principles.
内容的提问来源于stack exchange,提问作者Waleed Naveed

