constructor(){} 接受数据 声明数据和方法
render()渲染页面
componentDidMount() 页面结构加载完成 这里可以写数据请求
componentDidUpdate(){} 页面更新完成
componentwillUnmount(){} 组件离开
shouldComponentUpdate(nextProps,nextState){} 是否渲染到页面上去
页面打开会执行constructor(){} render(){} componentDidMount(){}这几个生命周期函数
执行了this.setState({}) 会执行render(){} componentDidUpdate(){}
执行了forceUpdate()强制更新也会触发render(){} componentDidUpdate(){}
React 组件的生命周期有三个不同的阶段:
- 初始渲染阶段:这是组件即将开始其生命之旅并进入 DOM 的阶段。
- 更新阶段:一旦组件被添加到 DOM,它只有在 prop 或状态发生变化时才可能更新和重新渲染。这些只发生在这个阶段。
- 卸载阶段:这是组件生命周期的最后阶段,组件被销毁并从 DOM 中删除。
import React, { Component } from 'react'
export default class Menu10 extends Component {
constructor(props) {//接收数据 声明数据和方法
super(props)
console.log("1")
this.state = {
num: 10
}
}
render() { //渲染页面
console.log(2)
return (
<div>
{this.state.num}
<button onClick={this.add}>+</button>
</div >
)
}
add = () => {
this.setState({
num: this.state.num + 1
})
}
shouldComponentUpdate(nextProps, nextState) {
// console.log(nextProps);
console.log(nextState);
if (nextState.num % 2 == 0) { //满足num是偶数才在页面上显示
return true
} else {
return false;
}
}
componentDidMount() {//这里写数据请求
console.log(3)
setTimeout(() => {
// this.setState({
// num: 999
// })
this.state.num = 888;
this.forceUpdate(); //强制更新会触发render()钩子函数 和componentDidUpdate()钩子函数
}, 3000);
}
componentDidUpdate() { //页面更新完成
console.log(4)
}
componentWillUnmount() {//组件离开
console.log("5")
}
}