Let say i have a class component myPapa inside which is am not using any constructor or super():
class myPapap extends React.Component{
render(){
this.state = {mom: 'dad'};
this.props.brother = 'sister';
alert(this.state + ' ' + this.props);
return(
<View>
Something ...
</View>
);
}
}
Which works perfect and alerts:
[object Object][object Object]
Which means that it we can call the this.props and this.state and it is working. So, if this thing is working then why i have to do:
class myPapap extends React.Component{
constructor(props){
super(props);
this.state = {mom: 'dad'};
this.props.brother = 'sister';
}
}
Please can anyone tell in easy explanation with example ?
The only place where you can assign this.state is the constructor.
As we all know, the reason why we use the state
in React component is that whenever the component's state has updated, it will trigger the component to be re-rendered so that its presentation reflect the component's state. In order to leverage this advantage provided by the component's state
, we have to obey the mechanism.
Moreover, the re-rendered process only happens when we update the component's state in an appropriate way which is using the setState()
method.
For more information, you could find it here: Do Not Modify State Directly
Your code this.props.brother = 'sister';
will not work for sure.
This is the demo: https://codesandbox.io/s/j354ypk645
You will get the error:
Cannot add property brother, object is not extensible
The reason is, according to the React Document Props Are Read Only, they said:
Props are Read-Only
Whether you declare a component as a function or a class, it must never modify its own props.
...
All React components must act like pure functions with respect to their props.
According to the React Document, section Constructor(), said:
If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.
And
The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.
Well then, you can use this.props.brother
in order to retrieve the value of this property which is passed from a parent component. However, this is only for get
, you are not supposed to set
a value to it. The reason has been explained in part two of this answer.