父组件
import React from 'react'
import Child from './Child'
export default class Life extends React.Component{
state = {
count: 0
}
handleMiu = () => {
this.setState({
count: this.state.count - 1
})
}
handleAdd = () => {
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<div>
<h2>{this.state.count}</h2>
<button onClick={this.handleAdd}>+</button>
<button onClick={this.handleMiu}>-</button>
<hr/>
<Child count={this.state.count} />
</div>
)
}
}
子组件
import React from 'react'
export default class Child extends React.Component{
componentWillMount () {
console.log('child will mount');
}
componentDidMount () {
console.log('child did mount');
}
componentWillReceiveProps(newProps) {
console.log('will receive props ' + newProps.count);
}
shouldComponentUpdate() {
console.log('should update');
return true
}
componentWillUpdate() {
console.log('will update');
}
componentDidUpdate() {
console.log('did update');
}
render() {
return (
<div>
<h2>{this.props.count}</h2>
</div>
)
}
}
点击相加的按钮,有两次shouldComponentUpdate,componentWillUpdate
和componentDidUpdate
却只有一次是什么原因?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…