To update the props
object in the child components, usually the life cycle method ComponentWillReceiveProps
is used. But I realized that the props
for the child component could be updated without listening for ComponentWillReceiveProps
.
For example, in the following component named App
, the child component Comp
is able to receive the props
without listening for the life cycle method ComponentWillReceiveProps
.
The main App
component:
import React from 'react';
import ReactDOM from 'react-dom';
import {Comp} from "./comp";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
this.incrementCounter = this.incrementCounter.bind(this);
}
componentDidMount() {
this.setState({
counter: 100
})
}
incrementCounter() {
this.setState({
counter: this.state.counter + 1
})
}
render() {
return (
<div>
<button onClick={this.incrementCounter}>Increment</button>
<br />
<br />
<Comp counter={this.state.counter}/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
and the child Comp
component:
import React from 'react';
export class Comp extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
componentDidUpdate(prevProps, prevState) {
console.log("prev props ", prevProps);
console.log("prev state", prevState)
}
render() {
return <span>Props received: {JSON.stringify(this.props)}</span>
}
}
Here is also the working demo of the above code I prepared
You will see that the child component Comp
receives property counter
without listening for any lifecycle method.
What does it mean? Am I missing anything?