網站首頁 編程語言 正文
前言
React函數式編程沒有生命周期,因此需要借助useEffect來實現。
useEffect的作用
- 發ajax請求獲取數據
- 設置訂閱/獲取定時器
- 手動更改真實DOM
useEffect的使用?
1.class組件
在class組件中可以使用生命周期函數,知道組件觸發的過程。
代碼如下(示例):
import React, { Component } from 'react'
export default class App extends Component {
constructor(p){
super(p)
this.state = {num: 0}
}
render() {
return (
<div>
<h2>{this.state.num}</h2>
<button onClick={this.addNum.bind(this)}>累加</button>
</div>
)
}
componentDidMount(){
console.log('Mount')
}
componentDidUpdate(){
console.log('Update')
}
componentWillUnmount(){
consoloe.log('Unmount')
}
addNum(){
this.setState({
num: this.state.num+1
})
}
}
生命周期(圖)
2.函數式組件
函數式組件中沒有自己的生命周期,需要使用useEffect模擬生命周期。
代碼如下(示例):
import React, { useState, useEffect } from 'react'
function App1(){
const [num, setNum] = useState(0);
const [num1, setNum1] = useState(1)
/*
1.第二個參數為空的情況:在初次渲染執行一次后,會監聽所有數據的更新,數據更新則會觸發useEffect()。(componentDidMount、componentDidUpdate)
2.第二個參數為[]的情況:回調函數只會在第一次render()后執行。(componentDidMount)
3.第二個參數為[監聽的元素]:在初次渲染執行一次后,只會監聽相應元素變化才會觸發回調函數。(componentDidMount、componentDidUpdate)
4.useEffect體中使用了return為一個函數,會在組件卸載前執(componentWillUnmount)
*/
useEffect(()=>{
console.log('useEffect')
}, [num])
return (
<div>
<h1>{num}</h1>
<button onClick={()=>setNum(num+1)}>累加</button>
<h1>{num1}</h1>
<button onClick={()=>setNum1(num1+1)}>累加</button>
</div>
)
}
export default App1;
總結
語法和說明
useEffect(()=>{
// 在此可以執行任何帶副作用操作
return ()=> { // 在組件卸載前執行
// 在此走一些收尾工作,如清除定時器/取消訂閱等
}
},[stateValue])// 如果指定的是[],回調函數只會在第一次render()后執行
//如果第二個參數不填,將會監聽所有數據的更新
可以把useEffect Hook 看做如下三個函數的組合
- componentDidMount()
- componentDidUpdate()
- componentWillUnmount()
原文鏈接:https://blog.csdn.net/m0_46165586/article/details/127541468
相關推薦
- 2022-09-19 用正則表達式匹配字符串中漢字及中文標點符號_正則表達式
- 2022-10-02 Pandas中的unique()和nunique()區別詳解_python
- 2022-06-18 Elasticsearch之基本查詢及組合查詢操作示例_其它綜合
- 2022-11-13 Error: EACCES: permission denied, access '/usr/loc
- 2023-04-24 Android?集成Google?Cast?異常問題解析_Android
- 2022-04-12 Git:解決Git向碼云中push文件報錯:! [rejected] master -
- 2023-04-18 C語言計算連續無序數組中缺省數字方法詳解_C 語言
- 2023-06-05 python中xlwt模塊的具體用法_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同步修改后的遠程分支