網(wǎng)站首頁 編程語言 正文
react組件的生命周期
- 1、什么是生命周期?
- 2、生命周期流程圖(舊)
- 2.1 、生命周期的三個(gè)階段(舊)
- 3、生命周期流程圖(新)
- 3.1、被棄用的三個(gè)鉤子函數(shù)
- 3.2、生命周期的三個(gè)階段(新)
需求:定義組件實(shí)現(xiàn)以下功能:
- 讓指定的文本做顯示 / 隱藏的漸變動(dòng)畫
- 從完全可見,到徹底消失,耗時(shí)2S
- 點(diǎn)擊“不活了”按鈕從界面中卸載組件
//1、創(chuàng)建組件
class Demo extends React.Component {
state = {opacity: 1}
death = () => {
//卸載組件
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
//組件完成掛載后執(zhí)行
componentDidMount() {
this.timer=setInterval(() => {
// 獲取原狀態(tài)
let {opacity} = this.state;
// 減小0.1
opacity -= 0.1
if (opacity <= 0) opacity = 1
this.setState({opacity})
}, 200)
}
//組件將要卸載時(shí)調(diào)用
componentWillUnmount(){
//清除定時(shí)器
clearInterval(this.timer)
}
//render調(diào)用時(shí)機(jī):初始化渲染、狀態(tài)更新之后
render() {
return (
<div>
<h1 style={{opacity: this.state.opacity}}>react感覺還是有點(diǎn)難滴!!!怎么辦?</h1>
<button onClick={this.death}>不活了</button>
</div>
)
}
}
//2、渲染虛擬DOM
ReactDOM.render(<Demo/>, document.getElementById('test'))
1、什么是生命周期?
- 組件從創(chuàng)建到死亡它會(huì)經(jīng)歷一些特定的階段。
- React組件中包含一系列勾子函數(shù)(生命周期回調(diào)函數(shù)), 會(huì)在特定的時(shí)刻調(diào)用。
- 我們在定義組件時(shí),會(huì)在特定的生命周期回調(diào)函數(shù)中,做特定的工作
2、生命周期流程圖(舊)
2.1 、生命周期的三個(gè)階段(舊)
-
初始化階段:
由ReactDOM.render()觸發(fā)—初次渲染- constructor()
- componentWillMount()
- render()
- componentDidMount()---------常用,一般在這個(gè)鉤子函數(shù)做一些初始化操作,例如:開啟定時(shí)器,發(fā)起網(wǎng)絡(luò)請求,訂閱消息等等…
-
更新階段
: 由組件內(nèi)部this.setSate()或父組件重新render觸發(fā)- shouldComponentUpdate()
- componentWillUpdate()
- render()--------必須使用的一個(gè)
- componentDidUpdate()
-
卸載組件
: 由ReactDOM.unmountComponentAtNode()觸發(fā)- componentWillUnmount()--------常用,一般在這個(gè)鉤子函數(shù)做一些收尾的事兒,例如:關(guān)閉定時(shí)器、取消定時(shí)器…
//1、創(chuàng)建組件
class Count extends React.Component {
//構(gòu)造器
constructor(props) {
console.log('count-constructor');
super(props);
this.state = {count: 0}
}
//將要掛載
componentWillMount() {
console.log('count-componentWillMount');
}
//掛載后
componentDidMount() {
console.log('count-componentDidMount');
}
//將要卸載
componentWillUnmount() {
//清除定時(shí)器
console.log('count-componentWillUnmount');
}
//控制組件是否更新的”閥門“
shouldComponentUpdate() {
console.log('count-shouldComponentUpdate');
return true;//返回false狀態(tài)無法更新,返回值為true,則更新
}
//組件將要更新
componentWillUpdate() {
console.log('count-componentWillUpdate');
}
//組件更新完成
componentDidUpdate() {
console.log('count-componentDidUpdate');
}
//count+1
add = () => {
// 獲取原狀態(tài)
let {count} = this.state;
this.setState({
count: count + 1
})
}
//卸載組件
unmount = () => {
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
//強(qiáng)制更新
force = () => {
//強(qiáng)制更新(無 控制組件是否更新的‘閥門’的步驟)
this.forceUpdate();
}
render() {
console.log('count-render');
let {count} = this.state;
return (
<div>
<h1>當(dāng)前求和為:{count}</h1>
<button onClick={this.add}>點(diǎn)擊+1</button>
<button onClick={this.unmount}>卸載組件</button>
<button onClick={this.force}>不更改任何狀態(tài)中的數(shù)據(jù),強(qiáng)制更新一下</button>
</div>
)
}
}
//父組件
class Father extends React.Component {
state = {carName: '寶馬'}
changeCar = () => {
this.setState({
carName: '馬自達(dá)'
})
}
render() {
return (<div>
<div>Father</div>
<button onClick={this.changeCar}>換車</button>
<Child carName={this.state.carName}></Child>
</div>
)
}
}
//子組件
class Child extends React.Component {
//組件將要接收父組件傳過來的新的屬性值(第一次不會(huì)執(zhí)行)
componentWillReceiveProps(props) {
console.log('Child-componentWillReceiveProps',props);
}
render() {
return (<div>我是Child組件,我從Father組件中接收到的車是:{this.props.carName}</div>)
}
}
//2、渲染虛擬DOM
// ReactDOM.render(<Count/>, document.getElementById('test'))
ReactDOM.render(<Father/>, document.getElementById('test'))
3、生命周期流程圖(新)
3.1、被棄用的三個(gè)鉤子函數(shù)
-
- componentWillMount
-
- componentWillReceiveProps
-
- componentWillUpdate
??現(xiàn)在使用會(huì)出現(xiàn)警告,需要加上UNSAFE_
前綴才能使用,以后可能會(huì)被徹底廢棄,不建議使用。
3.2、生命周期的三個(gè)階段(新)
-
初始化階段:
由ReactDOM.render()觸發(fā)—初次渲染- constructor()
- getDerivedStateFromProps
- render()
- componentDidMount()---------常用,一般在這個(gè)鉤子函數(shù)做一些初始化操作,例如:開啟定時(shí)器,發(fā)起網(wǎng)絡(luò)請求,訂閱消息等等…
-
更新階段:
由組件內(nèi)部this.setSate()或父組件重新render觸發(fā)- getDerivedStateFromProps
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate
- componentDidUpdate()
-
卸載組件:
由ReactDOM.unmountComponentAtNode()觸發(fā)- componentWillUnmount()--------常用,一般在這個(gè)鉤子函數(shù)做一些收尾的事兒,例如:關(guān)閉定時(shí)器、取消定時(shí)器…
//1、創(chuàng)建組件
class Count extends React.Component {
//構(gòu)造器
constructor(props) {
console.log('count-constructor');
super(props);
this.state = {count: 0}
}
// 若state的值在任何時(shí)候都取決于props,可以使用
//派生狀態(tài)(state的值在任何時(shí)候都取決于props.派生狀態(tài)會(huì)導(dǎo)致代碼冗余,并使組件難以維護(hù))
static getDerivedStateFromProps(props, state) {
//必須有返回值,null或state obj狀態(tài)對(duì)象
console.log('count-getDerivedStateFromProps', props, state);
return null;
// return props;//返回狀態(tài)對(duì)象會(huì)影響狀態(tài)的更新
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('count-getSnapshotBeforeUpdate', prevProps, prevState);
return 'xiao';
}
//掛載后
componentDidMount() {
console.log('count-componentDidMount');
}
//將要卸載
componentWillUnmount() {
//清除定時(shí)器
console.log('count-componentWillUnmount');
}
//控制組件是否更新的”閥門“
shouldComponentUpdate() {
console.log('count-shouldComponentUpdate');
return true;//返回false狀態(tài)無法更新,返回值為true,則更新
}
//組件更新完成(第三個(gè)參數(shù)為getSnapshotBeforeUpdate鉤子函數(shù)的返回值)
componentDidUpdate(prevProps, prevState,snapshotValue) {
console.log('count-componentDidUpdate',prevProps, prevState,snapshotValue);
}
//count+1
add = () => {
// 獲取原狀態(tài)
let {count} = this.state;
this.setState({
count: count + 1
})
}
//卸載組件
unmount = () => {
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
render() {
console.log('count-render');
let {count} = this.state;
return (
<div>
<h1>當(dāng)前求和為:{count}</h1>
<button onClick={this.add}>點(diǎn)擊+1</button>
<button onClick={this.unmount}>卸載組件</button>
</div>
)
}
}
//2、渲染虛擬DOM
ReactDOM.render(<Count count="99"/>, document.getElementById('test'))
getSnapshotBeforeUpdate的應(yīng)用場景:
??以特殊方式處理滾動(dòng)位置
//1、創(chuàng)建組件
class NewsList extends React.Component {
state = {newsArr: []}
componentDidMount() {
setInterval(() => {
// 獲取原來的狀態(tài)值
const {newsArr} = this.state;
// 模擬一條新聞
const news = '新聞' + (newsArr.length + 1);
// 更新狀態(tài)
this.setState({
newsArr: [news, ...newsArr]
})
}, 1000)
}
getSnapshotBeforeUpdate() {
return this.refs.list.scrollHeight
}
componentDidUpdate(prevProps, prevState, snapshotValue) {
this.refs.list.scrollTop += this.refs.list.scrollHeight - snapshotValue;
}
render() {
return (
<div className="list" ref="list">
{this.state.newsArr.map((item, index) => {
return <div className="news" key={index}>{item}</div>
})}
</div>
)
}
}
ReactDOM.render(<NewsList/>, document.getElementById('test'))
原文鏈接:https://blog.csdn.net/fangqi20170515/article/details/126052535
相關(guān)推薦
- 2022-07-06 Python3?DataFrame缺失值的處理方法_python
- 2023-05-24 python實(shí)現(xiàn)對(duì)AES加密的視頻數(shù)據(jù)流解密的方法_python
- 2022-10-18 C++函數(shù)模板與重載解析超詳細(xì)講解_C 語言
- 2022-03-25 .NET提取?Thread?中返回值詳情_ASP.NET
- 2021-12-03 前端異常502?bad?gateway的原因和解決辦法_nginx
- 2022-08-22 Python利用字典和列表實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)_python
- 2022-08-04 如何利用python實(shí)現(xiàn)列表嵌套字典取值_python
- 2022-09-03 Matplotlib中文亂碼的兩種詳細(xì)解決方案_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支