網站首頁 編程語言 正文
useEffect代替常用生命周期函數
原始生命周期函數
componentDidMount
componentDidUpdate
componentWillUnmount
采用原始的方式把計數器的Demo增加兩個生命周期函數componentDidMount和componentDidUpdate。
分別在組件第一次渲染后在瀏覽器控制臺打印出計數器結果和在每次計數器狀態發生變化后打印出結果。
代碼如下:
import React, { Component } from 'react'; class Example3 extends Component { constructor(props) { super(props); this.state = { count:0 } } componentDidMount(){ console.log(`ComponentDidMount=>You clicked ${this.state.count} times`) } componentDidUpdate(){ console.log(`componentDidUpdate=>You clicked ${this.state.count} times`) } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={this.addCount.bind(this)}>Chlick me</button> </div> ); } addCount(){ this.setState({count:this.state.count+1}) } } export default Example3;
React首次渲染和之后的每次渲染都會調用一遍useEffect函數,而之前我們要用兩個生命周期函數分別表示首次渲染(componentDidMonut)和更新導致的重新渲染(componentDidUpdate)。
組件中經常用到componentWillUnmount生命周期函數(組件將要被卸載時執行)。比如我們的定時器要清空,避免發生內存泄漏;比如登錄狀態要取消掉,避免下次進入信息出錯。
app.js
import React, { useState , useEffect } from 'react'; import { BrowserRouter as Router, Route, Link } from "react-router-dom" function Index() { useEffect(()=>{ console.log('useEffect=>老弟你來了!Index頁面') return ()=>{ console.log('老弟,你走了!Index頁面') } },[]) return <h2>JSPang.com</h2>; } function List() { useEffect(()=>{ console.log('useEffect=>老弟,你來了!List頁面') return ()=>{ console.log('老弟,你走了!List頁面') } }) return <h2>List-Page</h2>; } function App(){ const [ count , setCount ] = useState(0); useEffect(()=>{ console.log(`useEffect=>You clicked ${count} times`) return ()=>{ console.log('====================') } },[count]) return ( <div> <p>You clicked {count} times</p> <button onClick={()=>{setCount(count+1)}}>click me</button> <Router> <ul> <li> <Link to="/">首頁</Link> </li> <li><Link to="/list/">列表</Link> </li> </ul> <Route path="/" exact component={Index} /> <Route path="/list/" component={List} /> </Router> </div> ) } export default App;
index.js
import React from "react"; import {render} from "react-dom" import App from "./components/app" import {BrowserRouter} from "react-router-dom"; //渲染組件,我們使用react-router組件渲染組件時需要使用路由器組件標簽,我們可以使用"<BrowserRouter>"或者是"<HashRouter>"。但需要注意喲,這是一個SPA應用喲~ render( ( <BrowserRouter> <App /> </BrowserRouter> ), document.getElementById("root") )
PS:
useEffect的第二個參數:
實現類似componentWillUnmount的效果,它是一個數組,數組中可以寫入很多狀態對應的變量,意思是當狀態值發生變化時,我們才進行解綁。
如果我們想每次count發生變化,我們都進行解綁,只需要在第二個參數的數組里加入count變量就可以了但是當傳空數組[]時,就是當組件將被銷毀時才進行解綁,這也就實現了componentWillUnmount的生命周期函數。
對React Hooks(useState和useEffect) 的總結思考
一、為什么用React Hooks(面向生命周期編程變成了面向業務邏輯編程)
Hooks是React16.8版本后新增加的特性,目的是讓你用函數組件的寫法代替原來的類組件寫法,同時讓函數組件支持state,同時用useEffect代替原來的生命周期的業務功能編寫代碼
風格,目的就是解決原來用class寫組件的痛點,痛點有哪些自行查閱資料,主要有:
(1)選擇性煩惱:是使用狀態組件還是無狀態組件? ? 擁有了hooks后,現在一切組件均是Function。
(2)搞不清生命周期的鉤子函數? ?擁有了hooks后,生命周期鉤子函數可以先丟一邊了。
(3)組件的this搞暈了?擁有了hooks后,不需面對this.
二、useState理解
1.useState是異步的,定義方法(語法叫數組解構寫法),例如:
// 聲明一個叫 “count” 的 state 變量? ?const [count, setCount] = useState(0); // 更新state <button onClick={() => setCount(count + 1)}> ? ? Click me ? </button>
2. state變量可以定義多個,也可以存儲對象和數組,這邊有一個規則:它總是替換它,而不象class一樣合并它,即有閉包的概念。
三、useEffect的理解(原則:讓你忘記類組件的生命周期的函數寫法)
useEffect出現的需求背景:我們只想在 React 更新 DOM 之后運行一些額外的代碼 ? (所以叫副作用函數)
(一) 它是一個鉤子函數的定義,即對于dom的渲染后會產生相應的副作用(這個副作用中定義相關的功能),達于原來類組件的對生命周期函數一樣的應用效果,但比它更靈活省事。
(二)定義一個useEffect主要分為四種定義方法(總結:需不要return,需不要第二個參數,第二個參數要不要[]):
- 1.每次渲染都要執行:則第二個參數不需要。
- 2.在組件銷毀或者調用函數前調用。: ? 則第一個參數中增加return語句。
- 3.只在組件掛載時執行一次:則第二個參數用空數組:[].
- 4.只在某一個state或者prop值發生變化后,才執行,則第二個參數[變量名]。
(三)useEffect可以定義多個,把功能實現進行分離。
(四)useEffect 使用規則:
- 1.只在最頂層使用 Hook
- 2.只在 React 函數中調用 Hook
四、useState和useEffect聲明時有先后順序
產生的結果是不一樣,所以根據業務需要靈活確定他們先后順序的組合。
原文鏈接:https://blog.csdn.net/fwk19840301/article/details/122746267
相關推薦
- 2022-07-21 element 中loading顏色的修改
- 2022-04-18 C語言?簡單粗暴的笨方法找水仙花數_C 語言
- 2023-10-14 List排序問題
- 2022-07-08 Pyhacker實現端口掃描器_python
- 2022-09-09 Redis中ZSet的具體使用_Redis
- 2023-05-22 python中decimal模塊的用法_python
- 2022-08-18 R語言ComplexHeatmap繪制復雜熱圖heatmap_R語言
- 2023-04-02 Python中time庫的使用(日期時間)_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同步修改后的遠程分支