组件更新的过程:componentWillReceiveProps => shouldComponentUpdate => componentWillUpdate => render => componentDidUpdate
<script type="text/babel">
class A extends React.Component{
state = {carName: '奔驰'}
changeCar = () => {
this.setState({carName: '雅阁'})
}
render () {
return (
<div>
<h1>A</h1>
<h2>{this.state.carName}</h2>
<button onClick={this.changeCar}>换车</button>
<B carName={this.state.carName} />
</div>
)
}
}
class B extends React.Component{
// 组件将要接收(新的)props,父组件第一次渲染不会调用
componentWillReceiveProps(props){
console.log('B------------------------componentWillReceiveProps', props)
}
// 控制组件更新的阀门
shouldComponentUpdate(){
console.log('B------------------------shouldComponentUpdate')
return true
}
// 组件将要更新
componentWillUpdate(){
console.log('B------------------------componentWillUpdate')
}
// 组件完成更新
componentDidUpdate(){
console.log('B------------------------componentDidUpdate')
}
render () {
console.log('B------------------------render')
return (
<div>我是B组件,我接收的参数是:{this.props.carName}</div>
)
}
}
ReactDOM.render(<A />,document.getElementById('test'))
</script>