I want store custom instance of class in component state, but i don't know how change data on correct way
Before change instance i make clone of object.
For example i have a custom object with some properties:
this.state={
user: new User();
}
when need change data i make
const user = _.cloneDeep(this.state.user);
user.setSettings(/*some object of settings*/)
this.setState({user});
It's ok use cloneDeep every time? Maybe there's a better way change data and do not break react life cycles?
It's generally inappropriate to use cloneDeep
on class instances since a class can have instantiation logic that breaks when an instance is cloned. It's preferable to create a new class instance with new
, a class also should support cloning in order for new instance to be successfully hydrated from existing instance:
Foo.clone(fooInstance)
Where clone
is something like:
class Foo {
static clone(instance) {
const barArg = instance.bar;
const bazarg = instance.baz;
return new Foo(barArg, bazArg);
}
...
}
This puts additional constraints on class design.
Since immutable state is idiomatic to React, the use of class instances complicates state management because of these concerns. This is the reason why it's preferable to use plain objects for React state.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.