Answer the question
In order to leave comments, you need to log in
I'm making an SDK. How to explain to the user whether the getter is immutable or mutable?
I apologize for being stubborn. Both the concepts implemented in my SDK and the question itself.
Here is
class Cat {
...
}
clone
! var cat = new Cat();
cat.color = Colors.BLACK;
var cat2 = cat.clone();
cat2.color = Colors.RED;
CatPair
in it 2 fieldsCat
var catPair = new CatPair();
catPair.male.color = Colors.BLACK;
CatValue
. In which there will also be a field\property Cat
. And here it should work differently. CatValue
is: CatValue
at the same time, it will lie in the React state and store the state of the form fields. And when the fields are changed, it will try to form a cat, and if this does not work out, then it will return errors, which will also be placed in the state in order to immediately display them to the user. CatValue
it should return a cat, that is, an instance of the classCat
, and further work will be with him. CatValue
is stored in the state and therefore must be immutable. const { catValue } = this.state
catValue.cat.colors = Color.BLACK
const { catValue } = this.state
const newValue = catValue.changeColor(e.target.value)
setState({ catValue: newValue })
class CatValue{
...
get cat() {
return this._cat.clone()
}
...
}
catValue.buildCat().color = Colors.BLACK;
catValue.cloneCat().color = Colors.BLACK;
Answer the question
In order to leave comments, you need to log in
The cat object is not aware of the state's immutability requirements. Therefore, it is better to postpone these dances to the same place where immutability is required.
Alternatively, use immer to change deep properties without worrying about immutability:
import produce from "immer"
const nextState = produce(this.state, draft => {
// тут можно всё менять, не беспокоясь об иммутабельности
const { catValue } = draft;
catValue.cat.colors = Color.BLACK;
});
this.setState(nextState);
import produce from "immer"
const { catValue } = this.state;
const nextCatValue = produce(catValue, draft => {
// тут можно всё менять, не беспокоясь об иммутабельности
catValue.cat.colors = Color.BLACK;
});
this.setState({ catValue: nextCatValue });
Since normal readonly fields were not delivered to JS,
class Cat
{
constructor(color) {
this._color = color;
}
get color() {
return this._color;
}
}
const cat = new Cat('white');
console.log(cat.color)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question