同一API返回对象赋值后数组联动修改问题求助
问题原因
你遇到的问题本质是引用类型的赋值特性:在TypeScript/JavaScript里,对象和数组都是引用类型,当你把API返回的response同时赋值给sessionDisplay和sessionBase时,这两个变量并没有各自拥有独立的对象实例,而是同时指向内存中同一个对象。所以你修改sessionDisplay.Hearings的时候,实际上是在修改那个共享的对象里的数组,sessionBase自然也会同步变化。
解决方法
要让两个变量各自持有独立的原始数据和展示数据,你需要对API返回的response做深拷贝,生成两个完全独立的对象实例:
方法1:JSON序列化反序列化(简单通用,适合纯数据对象)
如果你的ISessionViewWrapperModel里没有函数、循环引用这类无法被JSON序列化的内容,这是最简便的方式:
this.appService.getCourtSessionWithHearings(Number(this.apiUser?.Id), this.sessionId).subscribe((response) => { // 深拷贝生成两个独立对象 this.sessionBase = JSON.parse(JSON.stringify(response)); this.sessionDisplay = JSON.parse(JSON.stringify(response)); });
方法2:扩展运算符+数组拷贝(适合嵌套不深的对象)
如果对象层级简单,也可以手动拷贝顶层属性和嵌套数组:
this.appService.getCourtSessionWithHearings(Number(this.apiUser?.Id), this.sessionId).subscribe((response) => { this.sessionBase = { ...response, Hearings: [...response.Hearings] // 单独拷贝Hearings数组 }; this.sessionDisplay = { ...response, Hearings: [...response.Hearings] }; });
方法3:手动递归深拷贝(处理复杂对象)
如果你的对象有多层嵌套或者包含特殊类型(比如Date、函数),可以写一个递归拷贝函数:
function deepClone<T>(obj: T): T { if (obj === null || typeof obj !== 'object') return obj; // 处理数组 if (Array.isArray(obj)) { return obj.map(item => deepClone(item)) as unknown as T; } // 处理对象 const clonedObj = {} as T; for (const key in obj) { if (obj.hasOwnProperty(key)) { clonedObj[key] = deepClone(obj[key]); } } return clonedObj; } // 在订阅里使用 this.appService.getCourtSessionWithHearings(Number(this.apiUser?.Id), this.sessionId).subscribe((response) => { this.sessionBase = deepClone(response); this.sessionDisplay = deepClone(response); });
这样处理后,sessionBase会一直保留原始的API返回数据,sessionDisplay的修改就不会影响到它了,不需要重复调用API。
内容的提问来源于stack exchange,提问作者steveareeno
相关产品推荐
相关产品推荐

