react生命周期
生命周期图
包含挂载、更新、销毁三个环节
生命周期演示
包含两个组件FaComponents
和ClassComponent
。为了验证props的变化,所以追踪的是ClassComponent
的钩子函数。
第一次加载后输出:
//首次加载-挂载
constructor
componentWillMount
render
componentsDidMount
//点击"加一"按钮更新state
addNum
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
//点击destroy
componentWillUnmount
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
//class声明组件
class ClassComponent extends React.Component {
constructor(props){
super(props)
console.log('constructor')
this.state = {
num:1,
}
}
addNum(){
console.log('addNum')
let number = this.state.num
number += 1
this.setState({
num:number,
})
}
componentWillMount(){
console.log('componentWillMount')
}
componentDidMount(){
console.log('componentsDidMount')
}
componentWillReceiveProps(){
console.log('componentWillReceiveProps')
}
shouldComponentUpdate(){
console.log('shouldComponentUpdate')
return true
}
componentWillUpdate(){
console.log('componentWillUpdate')
}
componentDidUpdate(){
console.log('componentDidUpdate')
}
componentWillUnmount(){
console.log('componentWillUnmount')
}
componentDidCatch(){
console.log('componentWillUnmount')
}
render(){
console.log('render')
return (
<div>
<h1>{this.props.v1}</h1>
<span>{this.state.num}</span>
<button onClick={()=>{this.addNum()}}>加一</button>
</div>
)
}
}
class FaComponents extends React.Component{
constructor(props){
super()
this.state={
str:'hello redux',
isShow:true,
btnTxt:'destroy',
}
}
changeTitle(){
return ()=>{
let temp = this.state.str
temp += '123'
this.setState({
str:temp,
})
}
}
destroyChild(){
let temp = {
'isShow':!this.state.isShow,
'btnTxt':this.state.isShow?'show':'destroy'
}
this.setState({
...temp
})
}
render(){
return (
<div>
<button onClick={this.changeTitle()}>changeTitle</button>
<button onClick={()=>{this.destroyChild()}}>{this.state.btnTxt}</button>
{this.state.isShow ? <ClassComponent v1={this.state.str} /> : null}
</div>
)
}
}
ReactDOM.render(
<div>
<FaComponents></FaComponents>
</div>,
document.getElementById('example')
);
</script>
</body>
</html>