如何在不覆盖 React 中的其他项目的情况下设置对象的状态

时间:2021-06-03 00:56:50

标签: reactjs react-native react-redux rxjs react-hooks

我在反应中有一个状态,它是来自外部类的对象

类示例:

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 并保持其他属性完好无损?

1 个答案:

答案 0 :(得分:0)

你可以这样做。

this.setState({
  customerObj : { 
    ...this.state.customerObj,
    tm_last_name: e.value 
  }
});  

...Operator 允许您保留旧的 customerObj 的现有属性,而 tm_last_name: e.value 将仅覆盖 tm_last_name