I have a question regarding the object this in class Components.
import React from "react";
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0,
age: 30,
names: {
fn: 'Naruto',
ln: 'Uzumaki'
}
};
this.ref = this.state;
console.log('constructor');
}
update = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
console.log(Object.is(this.state, this.ref), this.state, this.ref);
console.log(this.state.names === this.ref.names);
return <div className="App">
{this.state.count}
<button onClick={this.update}>click</button>
</div>;
}
}
export default App;
o/p after the initial render:
constructor
true
{count: 0, age: 30, names: Object}
{count: 0, age: 30, names: Object}
true
o/p after the subsequent renders:
false
{count: 1, age: 30, names: Object}
{count: 0, age: 30, names: Object}
true
false
{count: 2, age: 30, names: Object}
{count: 0, age: 30, names: Object}
true
false
{count: 3, age: 30, names: Object}
{count: 0, age: 30, names: Object}
true
Why the this.ref the points to this.state variable are different in each render after the initial one?
If the Objects are merged in by the setState call then this.state and this.ref must be pointing to the same object after each render, right? Can someone enlighten me?
Does that mean React maintains its own state objectThey probably just do something likethis.state = {...this.state, ...updatedState}. Ie, overwritethis.statewith a new object.