gpt4 book ai didi

javascript - 在保留类类型的同时为嵌套对象 react setState

转载 作者:行者123 更新时间:2023-11-29 10:58:02 26 4
gpt4 key购买 nike

从这个问题延伸React Set State For Nested Object

更新嵌套状态的方法是分解对象并重新构造它,如下所示:

this.setState({ someProperty: { ...this.state.someProperty, flag: false} });

但是,这对我来说是个问题,因为它不会保留组件类(下面有更多详细信息)。我的目标是让我的状态结构如下:

this.state = {
addressComponent: {
street: '',
number: '',
country: ''
},
weather: {
/* some other state*/
}
}

为了让我的生活更轻松,我创建了一个简单的地址类,它为我构建对象并具有一些其他实用功能,例如验证。

class AddressComponent {
constructor(street, number, country) {
this.street = street;
this.number = number;
this.country = country;
}

validate() {
if (this.street && this.number, this.country) {
return true;
}
return false;
}
}

这允许我将状态的初始化更改为:

this.state = {
addressComponent : new AddressComponent(),
weather: new WeatherComponent();
}

this will allow my view component to perform nice things like

if (this.state.addressComponent.validate()) {
// send this state to parent container
}

这种方法的问题是,如果我想改变像国家这样的单一信息并使用上面的 Stack Overflow 方法,例如:

this.setState({addressComponent: {...addressComponent, country: 'bluh'}})

这样做意味着解析的 addressComponent 不再是 AddressComponent 类的一部分,因此没有 validate() 函数

为了解决这个问题,我每次都会重新创建一个新的 AddressComponent 类:

this.setState({addressComponent: new AddressComponent(this.state.street, this.state.number, 'bluh');

但这看起来很奇怪。

我做错了吗?有更好的方法吗?在 React 中使用这样的类是否可以接受?

最佳答案

对于 React 状态,不希望使用普通对象以外的任何东西来避免这种情况。使用类实例也会使状态的序列化和反序列化变得更加复杂。

AddressComponent 的存在是不合理的,它不会从类中获益。

相同的代码可以用普通对象重写为函数式:

const validateAddress = address => !!(street && address.number && address.country);
...

if (validateAddress(this.state.address)) {
// send this state to parent container
}

关于javascript - 在保留类类型的同时为嵌套对象 react setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com