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 ?
Firstly,
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'sstate
, 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
Secondly,
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:
The reason is, according to the React Document Props Are Read Only, they said:
Finally,
According to the React Document, section Constructor(), said:
And
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 forget
, you are not supposed toset
a value to it. The reason has been explained in part two of this answer.