網站首頁 編程語言 正文
react組件的生命周期
- 1、什么是生命周期?
- 2、生命周期流程圖(舊)
- 2.1 、生命周期的三個階段(舊)
- 3、生命周期流程圖(新)
- 3.1、被棄用的三個鉤子函數
- 3.2、生命周期的三個階段(新)
需求:定義組件實現以下功能:
- 讓指定的文本做顯示 / 隱藏的漸變動畫
- 從完全可見,到徹底消失,耗時2S
- 點擊“不活了”按鈕從界面中卸載組件
//1、創建組件
class Demo extends React.Component {
state = {opacity: 1}
death = () => {
//卸載組件
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
//組件完成掛載后執行
componentDidMount() {
this.timer=setInterval(() => {
// 獲取原狀態
let {opacity} = this.state;
// 減小0.1
opacity -= 0.1
if (opacity <= 0) opacity = 1
this.setState({opacity})
}, 200)
}
//組件將要卸載時調用
componentWillUnmount(){
//清除定時器
clearInterval(this.timer)
}
//render調用時機:初始化渲染、狀態更新之后
render() {
return (
<div>
<h1 style={{opacity: this.state.opacity}}>react感覺還是有點難滴!!!怎么辦?</h1>
<button onClick={this.death}>不活了</button>
</div>
)
}
}
//2、渲染虛擬DOM
ReactDOM.render(<Demo/>, document.getElementById('test'))
1、什么是生命周期?
- 組件從創建到死亡它會經歷一些特定的階段。
- React組件中包含一系列勾子函數(生命周期回調函數), 會在特定的時刻調用。
- 我們在定義組件時,會在特定的生命周期回調函數中,做特定的工作
2、生命周期流程圖(舊)
2.1 、生命周期的三個階段(舊)
-
初始化階段:
由ReactDOM.render()觸發—初次渲染- constructor()
- componentWillMount()
- render()
- componentDidMount()---------常用,一般在這個鉤子函數做一些初始化操作,例如:開啟定時器,發起網絡請求,訂閱消息等等…
-
更新階段
: 由組件內部this.setSate()或父組件重新render觸發- shouldComponentUpdate()
- componentWillUpdate()
- render()--------必須使用的一個
- componentDidUpdate()
-
卸載組件
: 由ReactDOM.unmountComponentAtNode()觸發- componentWillUnmount()--------常用,一般在這個鉤子函數做一些收尾的事兒,例如:關閉定時器、取消定時器…
//1、創建組件
class Count extends React.Component {
//構造器
constructor(props) {
console.log('count-constructor');
super(props);
this.state = {count: 0}
}
//將要掛載
componentWillMount() {
console.log('count-componentWillMount');
}
//掛載后
componentDidMount() {
console.log('count-componentDidMount');
}
//將要卸載
componentWillUnmount() {
//清除定時器
console.log('count-componentWillUnmount');
}
//控制組件是否更新的”閥門“
shouldComponentUpdate() {
console.log('count-shouldComponentUpdate');
return true;//返回false狀態無法更新,返回值為true,則更新
}
//組件將要更新
componentWillUpdate() {
console.log('count-componentWillUpdate');
}
//組件更新完成
componentDidUpdate() {
console.log('count-componentDidUpdate');
}
//count+1
add = () => {
// 獲取原狀態
let {count} = this.state;
this.setState({
count: count + 1
})
}
//卸載組件
unmount = () => {
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
//強制更新
force = () => {
//強制更新(無 控制組件是否更新的‘閥門’的步驟)
this.forceUpdate();
}
render() {
console.log('count-render');
let {count} = this.state;
return (
<div>
<h1>當前求和為:{count}</h1>
<button onClick={this.add}>點擊+1</button>
<button onClick={this.unmount}>卸載組件</button>
<button onClick={this.force}>不更改任何狀態中的數據,強制更新一下</button>
</div>
)
}
}
//父組件
class Father extends React.Component {
state = {carName: '寶馬'}
changeCar = () => {
this.setState({
carName: '馬自達'
})
}
render() {
return (<div>
<div>Father</div>
<button onClick={this.changeCar}>換車</button>
<Child carName={this.state.carName}></Child>
</div>
)
}
}
//子組件
class Child extends React.Component {
//組件將要接收父組件傳過來的新的屬性值(第一次不會執行)
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、被棄用的三個鉤子函數
-
- componentWillMount
-
- componentWillReceiveProps
-
- componentWillUpdate
??現在使用會出現警告,需要加上UNSAFE_
前綴才能使用,以后可能會被徹底廢棄,不建議使用。
3.2、生命周期的三個階段(新)
-
初始化階段:
由ReactDOM.render()觸發—初次渲染- constructor()
- getDerivedStateFromProps
- render()
- componentDidMount()---------常用,一般在這個鉤子函數做一些初始化操作,例如:開啟定時器,發起網絡請求,訂閱消息等等…
-
更新階段:
由組件內部this.setSate()或父組件重新render觸發- getDerivedStateFromProps
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate
- componentDidUpdate()
-
卸載組件:
由ReactDOM.unmountComponentAtNode()觸發- componentWillUnmount()--------常用,一般在這個鉤子函數做一些收尾的事兒,例如:關閉定時器、取消定時器…
//1、創建組件
class Count extends React.Component {
//構造器
constructor(props) {
console.log('count-constructor');
super(props);
this.state = {count: 0}
}
// 若state的值在任何時候都取決于props,可以使用
//派生狀態(state的值在任何時候都取決于props.派生狀態會導致代碼冗余,并使組件難以維護)
static getDerivedStateFromProps(props, state) {
//必須有返回值,null或state obj狀態對象
console.log('count-getDerivedStateFromProps', props, state);
return null;
// return props;//返回狀態對象會影響狀態的更新
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('count-getSnapshotBeforeUpdate', prevProps, prevState);
return 'xiao';
}
//掛載后
componentDidMount() {
console.log('count-componentDidMount');
}
//將要卸載
componentWillUnmount() {
//清除定時器
console.log('count-componentWillUnmount');
}
//控制組件是否更新的”閥門“
shouldComponentUpdate() {
console.log('count-shouldComponentUpdate');
return true;//返回false狀態無法更新,返回值為true,則更新
}
//組件更新完成(第三個參數為getSnapshotBeforeUpdate鉤子函數的返回值)
componentDidUpdate(prevProps, prevState,snapshotValue) {
console.log('count-componentDidUpdate',prevProps, prevState,snapshotValue);
}
//count+1
add = () => {
// 獲取原狀態
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>當前求和為:{count}</h1>
<button onClick={this.add}>點擊+1</button>
<button onClick={this.unmount}>卸載組件</button>
</div>
)
}
}
//2、渲染虛擬DOM
ReactDOM.render(<Count count="99"/>, document.getElementById('test'))
getSnapshotBeforeUpdate的應用場景:
??以特殊方式處理滾動位置
//1、創建組件
class NewsList extends React.Component {
state = {newsArr: []}
componentDidMount() {
setInterval(() => {
// 獲取原來的狀態值
const {newsArr} = this.state;
// 模擬一條新聞
const news = '新聞' + (newsArr.length + 1);
// 更新狀態
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
相關推薦
- 2022-06-12 Unity?使用tiledmap解析地圖的詳細過程_C#教程
- 2023-03-05 Redis緩存工具封裝實現_Redis
- 2022-12-24 MobPush?for?Flutter集成準備_IOS
- 2022-03-24 C語言make和Makefile介紹及使用_C 語言
- 2022-05-18 python?turtle繪制多邊形和跳躍和改變速度特效_python
- 2022-06-14 一文帶你搞懂Numpy中的深拷貝和淺拷貝_python
- 2022-07-10 css盒子塌陷及其解決方法
- 2023-04-03 python中super().__init__()作用詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支