这篇文章将为大家详细讲解有关React中生命周期的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
两张图带你理解 React的生命周期
React的生命周期(旧)
class Life extends React.Component{
// 构造器
constructor(props){
console.log('Life构造器---constructor');
super(props)
this.state={num:0}
}
// 计算+1功能
add=()=>{
const {num} = this.state
this.setState({num:num+1})
}
// 删除组件
death=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('text'))
}
force=()=>{
this.forceUpdate()
}
// 将要挂载
componentWillMount(){
console.log('Life将要挂载---componentWillMount');
}
// 已经挂载
componentDidMount(){
console.log('Life已经挂载---componentDidMount');
}
// 删除触发
componentWillUnmount(){
console.log('Life删除触发---componentWillUnmount');
}
// 是否应该改变数据
shouldComponentUpdate(){
console.log('Life是否改变数据---shouldComponentUpdate');
return true
}
// 将要改变数据
componentWillUpdate(){
console.log('Life将要改变数据---componentWillUpdate');
}
// 改变数据
componentDidUpdate(){
console.log('Life改变数据---componentDidUpdate');
}
render(){
console.log('Life---render');
const {num} = this.state
return(
<div>
<h2>计数器:{num}</h2>
<button onClick={this.add}>点我+1</button>
<button onClick={this.death}>删除</button>
<button onClick={this.force}>不更改任何状态的数据,强制更新</button>
</div>
)
}
}
// 渲染页面
ReactDOM.render(<Life />, document.getElementById('text'))
挂载步骤
更新步骤
删除
总结: 初始化阶段: 由ReactDOM.render()触发—初次渲染1. constructor() ---构造器
2. componentWillMount() ---将要挂载
3. render() ---render
4. componentDidMount() ---挂载时
更新阶段: 由组件内部this.setSate()或父组件重新render触发1. shouldComponentUpdate() ---是否要进行更改数据
2. componentWillUpdate() ---将要更新数据
3. render()
4. componentDidUpdate() ---更新数据
卸载组件: 由ReactDOM.unmountComponentAtNode()触发componentWillUnmount() ---卸载
React的生命周期(新)
生命周期的三个阶段(新)
初始化阶段: 由ReactDOM.render()触发—初次渲染
1. constructor()
2. getDerivedStateFromProps
3. render()
4. componentDidMount()更新阶段: 由组件内部this.setSate()或父组件重新render触发1. getDerivedStateFromProps
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate
5. componentDidUpdate()卸载组件: 由ReactDOM.unmountComponentAtNode()触发
1. componentWillUnmount()
重要的勾子
1.render:初始化渲染或更新渲染调用
2.componentDidMount:开启监听, 发送ajax请求
3.componentWillUnmount:做一些收尾工作, 如: 清理定时器
即将废弃的勾子
1.componentWillMount
2.componentWillReceiveProps
3.componentWillUpdate
现在使用会出现警告,下一个大版本需要加上UNSAFE_前缀才能使用,以后可能会被彻底废弃,不建议使用。
关于“React中生命周期的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。