Reputation: 57
I have a question. Perhaps a little silly.
For example i have class, with state and baseState, who linked to state inside construcor
class SomeStrangeClass extends Component {
constructor(props){
super(props);
this.state = {
confirmError:[],
};
this.baseState = this.state;
}
componentWillReceiveProps(nextProps){
console.log(this.state); //here i can have, for example, 3 confirmErrors...
console.log(this.baseState); // here i still have an empty array
this.setState(this.baseState);
}
...some strange code
}
Of course it is good for me. Simple reset of state))) But..why this.basestate is empty, meanwhile this.state is not.
Why javascript behaves as if did not create a reference to the object?
Thank you very mutch!
Upvotes: 1
Views: 178
Reputation: 169
When you do the assignment this.baseState = this.state
, you are assigning the value of this.state
at that time to the variable this.baseState
, essentially making a copy. If this.state
is updated with new variables after this, it does not reflect in the copy you made before.
Upvotes: 1
Reputation: 46331
With
this.baseState = this.state;
you are defining the completely new property of that React.Component
class.
I the constructor means at the specific time when you initialize your React.Component
object they will be equal.
It is a JavaScript feature to add new properties to any object dynamically.
Later on, when you execute setState()
method of the Component class only the predefined state
property will update and not the other one.
Here is the part of the source code for the React.Component
:
/**
* Module for creating composite components.
*
* @class ReactClass
*/
var ReactClass = {
createClass: function(spec) {
// To keep our warnings more understandable, we'll use a little hack here to
// ensure that Constructor.name !== 'Constructor'. This makes sure we don't
// unnecessarily identify a class without displayName as 'Constructor'.
var Constructor = identity(function(props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (__DEV__) {
warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: https://facebook.github.io/react/warnings/legacy-factories.html'
);
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
just to visualize what is inside the component.
Upvotes: 2