React的生命周期
生命周期的三个状态
- Mounting:将组件插入dom中
- Updating:将数据更新到dom中
- Unmounting:将组件移出dom中
生命周期中的钩子函数
- ComponentWillMount:组件将要被渲染,可以使用AJAX获取数据,添加动画前的类
- ComponentDidMount:组件渲染完毕,可以添加动画
- ComponentWillReceiveProps:组件将要接受props数据,查看接收props是什么数据
- ShouldComponentUpdate:组件接收到新的state或者props,判断是否更新,返回布尔值
- ComponentWillUpdate:组件将要被更新
- ComponentDidUpdate:组件将要更新
- ComponentWillUnmount:组件将要被卸载,一些关闭动作,如socket.close()
import React from 'react';
import ReactDOM from 'react-dom';
class Test extends React.Component {
constructor (props) {
super(props)
this.state = {
msg: 'hello world'
}
console.log('constructor');
}
componentWillMount() {
console.log('ComponentWillMount')
}
componentDidMount() {
console.log('componentDidMount');
}
componentWillReceiveProps() {
console.log('componentWillReceiveProps');
}
shouldComponentUpdate() {
console.log('shouldComponentUpdate');
return true
}
componentWillUpdate() {
console.log('ComponentWillUpdate');
}
componentDidUpdate() {
console.log('ComponentDidUpdate');
}
componentWillUnmount() {
console.log('ComponentWillUnmount');
}
render () {
console.log('render');
return (
<div>
<h1>{this.state.msg}</h1>
<button onClick={this.changeMsg}>修改msg</button>
</div>
)
}
changeMsg = ()=> {
this.setState({
msg: 'hello hello'
})
}
}
class Test1 extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: true
}
}
render () {
if (this.state.isShow) {
return (
<div>
<Test></Test>
<button onClick={this.removeTest}>移除Test组件</button>
</div>
)
} else {
return (
<div>
<h1>已经移除Test组件</h1>
</div>
)
}
}
removeTest = () => {
this.setState({
isShow: false
})
}
}
ReactDOM.render(
<Test1 />,
document.getElementById('root')
)
初次渲染的输出结果
点击修改组件内容
点击移除Test组件