***已编辑我刚刚意识到您正在尝试更改属性的名称。这不是我能帮忙的。我认为这只是类序列化/反序列化。
我刚刚打了几天这场战斗,我想我终于破解了它。这是对我有用的示例用户和地址。
import * as clone from 'clone'
import Address, { AddressFactory } from './Address'
import { classToPlain, plainToClass, Type } from 'class-transformer'
export class User {
name: string
userID: string
@Type(() => Address)
address: Address
constructor(name: string, userID: string, address: Address) {
this.name = name
this.userID = userID
this.address = address
}
copyObject(): User {
return clone<User>(this)
}
getObjectForSaving(): Record<string, unknown> {
return classToPlain(this)
}
}
export default User
export class UserFactory {
static fromVoid(): User {
return new User('name', 'userID', AddressFactory.fromVoid())
}
static fromJSON(jsonObjectData: User): User {
return plainToClass(User, jsonObjectData)
}
}
然后是地址模型
import { classToPlain, plainToClass } from "class-transformer"
import * as clone from 'clone'
export class Address {
num: number
street: string
city: string
state: string
zip: number
constructor(num: number, street: string, city: string, state: string, zip: number) {
this.num = num
this.street = street
this.city = city
this.state = state
this.zip = zip
}
copyObject(): Address {
return clone<Address>(this)
}
getObjectForSaving(): Record<string, unknown> {
return classToPlain(this)
}
}
export default Address
export class AddressFactory {
static fromVoid(): Address {
return new Address(0, '', '', '', 0)
}
static fromJSON(jsonObjectData: Address): Address {
return plainToClass(Address, jsonObjectData)
}
}
我使用工厂函数来生成新对象。可以是新的默认对象,也可以使用静态 fromJSON 构造函数实例化新的类实例。如果需要,您还可以创建其他工厂构造函数。
最后,我在 Redux 中更新状态时使用复制对象快速复制对象,以帮助实现不变性等...
祝你好运!