我在反应中有一个状态,它是来自外部类的对象
类示例:
export class Customers{
tm_name?: string | null;
tm_last_name?: string | null;
tm_gender?: string | null;
}
我导入了文件,然后我从那个类中创建和声明
状态示例:
this.state = {
customerObj: new Customers()
};
之后,如果我调试我的类并查看 customerObj 状态,它具有所有 3 个属性(空但它具有我的 3 个类属性)
问题是,当我尝试使用 setState 仅设置 customerObj 的一个值(如 tm_gender)时,它会删除所有其他属性,如 tm_name 和 tm_gender
setState 示例:
this.setState({
customerObj : {
tm_last_name: e.value }});
}
有没有办法只对某些状态/对象(customerObj)属性使用 setState 并保持其他属性完好无损?
答案 0 :(得分:0)
你可以这样做。
this.setState({
customerObj : {
...this.state.customerObj,
tm_last_name: e.value
}
});
...Operator 允许您保留旧的 customerObj
的现有属性,而 tm_last_name: e.value
将仅覆盖 tm_last_name