参考资料:简书:aermin
class MyComponent extends React.Component{
// 构造函数
constructor(props){
console.log('constructor');
super(props);
this.state = {
name:'zhangsan'
}
}
// 组件将要挂栽
componentWillMount(){
console.log('componentWillMount');
}
// 组件完成挂载
componentDidMount(){
console.log('componentDidMount');
}
// 默认返回 false 返回 true 组件页面内容才会更新
shouldComponentUpdate(){
console.log('shouldComponentUpdate');
return true;
}
// 组件将要更新
componentWillUpdate(){
console.log('componentWillUpdate');
}
// 组件完成更新
componentDidUpdate(){
console.log('componentDidUpdate');
}
// 组件将要卸载
componentWillUnmount(){
console.log('componentWillUnmount');
}
// 自定义函数
changeName = () => {
this.setState({
name:'lisi'
})
}
// 自定义函数
unmountComponent = () => {
// 手动卸载组件
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
}
// 组件渲染
render(){
console.log('render');
return (
<div>
<button onClick={this.changeName}>点击更改姓名:{this.state.name}</button>
<br/>
<br/>
<button onClick={this.unmountComponent}>卸载组件</button>
</div>
)
}
}
ReactDOM.render(<MyComponent age = {26} />,document.getElementById('root'));
其中还有一个生命周期函数,作为一个新手,不是很懂
componentWillReceiveProps(){
console.log('componentWillReceiveProps');
}
不过看官方文档好像有一个替代方案
getDerivedStateFromProps(){}
尚未点击更新状态前生命周期函数顺序展示
点击更新状态后生命周期顺序展示
手动卸载组件后生命周期顺序展示