When I change my state, I can read newData in Main Component but my update state doesn't go my ChildComponent. I read only initialData in my ChildComponent. Why doesn't go my new props to ChildComponent? or Why doesn't reRender my ChildComponent ?
class Main extends Component{
constructor(props) {
super(props);
this.state = {
data: "initalData",
}
}
componentDidMount(){
this.changeState();
}
changeState(){
this.setState({data: "newData"})
}
render(){
console.log("my data in Main :",this.state.data)
return(
<ChildComponent dataProps={this.state.data}>
)
}
class ChildComponent extends Component{
constructor(props) {
super(props);
const getData = props.dataProps;
console.log("getData is ",getData)
this.state = {
...,
}
}
}
It's because the constructor
of the class component only run once when you initialize it but not every render.
To always get the latest value, you would need to put them inside the class component body below the constructor.
Something like this:
class ChildComponent extends Component{
constructor(props) {
super(props);
this.state = {
...
}
}
const getData = this.props.dataProps;
console.log("getData is ", getData)
render() (
...
)
}