-
初始化组件
-
渲染组件
-
更新组件
-
删除组件
mounting 加载组件
constructor() 构造器函数 初始化数据状态 比如state的初始化
render() 返回一个 Virtual DOM
componentDidMount() Dom 节点插入之后调用的生命函数
网络请求
setState() 更改数据状态
class App extends React.Component {
constructor(){
super()
this.state = {
name : "张三"
}
console.log("组件初始化-------")
}
componentDidMount(){
console.log("DOM节点插入之后-------")
}
render(){
console.log("render------")
return <div>
<p>{this.state.name}</p>
</div>
}
}
ReactDOM.render(<App/>,document.getElementById("app"))
updating 更新组件 当状态数据发生改变的时候,会触发这个生命函数
render() 再次调用
componentDidUpdate() 数据状态更新之后会调用
DOM 操作
网络请求
setState()
class App extends React.Component{
constructor(){
super()
this.state = {
name:'张三'
}
console.log('=======组建初始化')
this.click = this.click.bind(this)
}
// 事件函数
click(){
this.setState({
name:'李四'
})
}
render(){
console.log('======render ')
return <div>
<p>hello react</p>
<h1>{this.state.name}</h1>
<button onClick = {this.click}>修改姓名</button>
<button onClick = { ()=>{ ReactDOM.unmountComponentAtNode(document.getElementById('app'))}}>卸载该组建</button>
</div>
}
//节点插入之后调用的生命函数
componentDidMount(){
console.log('componentDidMount=========节点插入之后调用的生命函数')
}
//组件更新之后会调用这个生命函数
componentDidUpdate(){
console.log('componentDidUpdate-------------')
}
//组建卸载之前调用
componentWillUnmount(){
console.log('componentWillUnmount----组建卸载之前调用')
}
}
ReactDOM.render(<App/>,document.getElementById('app'))
unmounting 卸载组件
componentWillUnmount() 组件在卸载之前会调用这个方法
-
清除 timer 计时器
-
取消网络请求
-
清除在
componentDidMount()
中创建的订阅
ReactDOM.unmountComponentAtNode(container)
用于卸载我们的组件
-
参数就是我们插入组件的容器,dom 对象,这个dom对象就是我们document.getElementById() 获取的根节点
案例 时钟
class Clock extends React.Component{
constructor(){
super()
this.state = {
time:new Date()
}
this.timer = null
}
clock(){
this.setState({
time:new Date()
})
}
//组建插
componentDidMount(){
this.timer = setInterval(()=>{
this.clock()
},1000)
}
componentWillUnmount(){
clearInterval(this.timer)
}
render(){
return <div>
<h1>计时器</h1>
<p>{this.state.time.toLocaleTimeString()}</p>
</div>
}
}
ReactDOM.render(<Clock/>,document.getElementById('app'))