網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
背景
介紹Hooks之前,首先要說(shuō)一下React的組件創(chuàng)建方式,一種是類(lèi)組件
,一種是純函數(shù)組件
,并且React團(tuán)隊(duì)希望,組件不要變成復(fù)雜的容器,最好只是數(shù)據(jù)流的管道。開(kāi)發(fā)者根據(jù)需要,組合管道即可。也就是說(shuō)組件的最佳寫(xiě)法應(yīng)該是函數(shù)
,而不是類(lèi)。
但是我們知道,在以往開(kāi)發(fā)中類(lèi)組件和純函數(shù)組件的區(qū)別是很大的,純函數(shù)組件有著類(lèi)組件不具備的多種特點(diǎn):
純函數(shù)組件沒(méi)有狀態(tài)
純函數(shù)組件沒(méi)有生命周期
純函數(shù)組件沒(méi)有this
這就注定,我們所推崇的函數(shù)組件,只能做UI展示的功能,涉及到狀態(tài)的管理與切換,我們不得不用類(lèi)組件或者redux,但我們知道類(lèi)組件的也是有缺點(diǎn)的,比如,遇到簡(jiǎn)單的頁(yè)面,代碼會(huì)顯得很重,并且每創(chuàng)建一個(gè)類(lèi)組件,都要去繼承一個(gè)React實(shí)例;至于Redux,更不用多說(shuō),很久之前Redux的作者就說(shuō)過(guò),“能用React解決的問(wèn)題就不用Redux”。
useState
useState():狀態(tài)鉤子。純函數(shù)組件沒(méi)有狀態(tài),useState()用于為函數(shù)組件引入狀態(tài)。
點(diǎn)擊加一效果,分別用類(lèi)組件和函數(shù)組件實(shí)現(xiàn)。可以看出用hooks寫(xiě)出的代碼更加精簡(jiǎn)。
const [count,setCount] = useState(0)
;//數(shù)組解構(gòu),相當(dāng)于下面三句話
let _useState = useState(0);
let count = _useState[0];
let setState = _useState[1]
類(lèi)組件
import React,{Component} from "react"; class App1 extends Component{ constructor(props) { super(props); this.state={ count:0 } } addCount(){ this.setState({count:this.state.count+1}) } render() { return() } } export default App1;you clicked {this.state.count} times
函數(shù)組件
使用sueState重寫(xiě)上面計(jì)數(shù)組件。
import React,{useState} from "react"; function App2(){ const [count,setCount] = useState(0);//數(shù)組解構(gòu) return() } export default App2;You cliked {count} times
多狀態(tài)聲明
使用多條語(yǔ)句聲明不同的狀態(tài)
import React,{useState} from "react"; function App3(){ const [name,setName] = useState('劉備');//數(shù)組解構(gòu) const [age,setAge] = useState(25); const [sex,setSex] = useState('男') return() } export default App3;姓名:{name}
年齡:{age}
性別:{sex}
useEffect
useEffect():副作用鉤子。可以用來(lái)更好的處理副作用,如異步請(qǐng)求等,Hooks的useEffect()也是為函數(shù)組件提供了處理副作用的鉤子。在類(lèi)組件中我們會(huì)把請(qǐng)求放在componentDidMount里面,在函數(shù)組件中我們可以使用useEffect()。
useEffect相當(dāng)于componentDidMount和componentDidUpdate。
缺點(diǎn):由于它是異步的因此不能實(shí)時(shí)處理。
類(lèi)組件中componentDidMount和componentDidUpdate
import React,{Component} from "react"; class App4 extends Component{ constructor(props) { super(props); this.state={ count:0 } } componentDidMount() { console.log(`componentDidMount=>you clicked ${this.state.count}`) } componentDidUpdate() { console.log(`componentDidUpdate=>you clicked ${this.state.count}`) } addCount(){ this.setState({count:this.state.count+1}) } render() { return() } } export default App4;you clicked {this.state.count} times
useEffect模擬類(lèi)組件中componentDidMount和componentDidUpdate
import React,{useState,useEffect} from "react"; function App5(){ const [count,setCount] = useState(0);//數(shù)組解構(gòu) useEffect(()=>{ console.log(`useEffect=>you clicked ${count} times`) }) return() } export default App5;You cliked {count} times
useEffect實(shí)現(xiàn)componmentWillUnment
先寫(xiě)兩個(gè)路由跳轉(zhuǎn)頁(yè)面,并配置路由
import React,{useState,useEffect} from "react"; import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom' function Index(){ returnIndex頁(yè)面
} function List(){ returnList頁(yè)面
} function App5(){ const [count,setCount] = useState(0);//數(shù)組解構(gòu) return() } export default App5;You cliked {count} times
- 首頁(yè)
- list
}/> }/>
使用useEffect表示進(jìn)入頁(yè)面的狀態(tài)。
解綁時(shí)使用return,這時(shí)發(fā)現(xiàn)我們點(diǎn)擊按鈕時(shí)也會(huì)發(fā)生改變,這是因?yàn)橹灰M件發(fā)生改變,它就會(huì)觸發(fā)解綁。解決方法使用第二個(gè)參數(shù)。
import React,{useState,useEffect} from "react"; import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom' function Index(){ useEffect(()=>{ console.log(`useEffect=>Index頁(yè)面`) return ()=>{ console.log('跳轉(zhuǎn)頁(yè)面') } }) returnIndex頁(yè)面
} function List(){ useEffect(()=>{ console.log(`useEffect=>List頁(yè)面`) }) returnList頁(yè)面
} function App5(){ const [count,setCount] = useState(0);//數(shù)組解構(gòu) return() } export default App5;You cliked {count} times
- 首頁(yè)
- list
}/> }/>
解綁限制,第二個(gè)參數(shù)是一個(gè)數(shù)組,如果數(shù)組為空表示頁(yè)面被銷(xiāo)毀觸發(fā),如果有變量,表示只有這個(gè)變量狀態(tài)變化才會(huì)觸發(fā)。
import React,{useState,useEffect} from "react"; import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom' function Index(){ useEffect(()=>{ console.log(`useEffect=>Index頁(yè)面`) return ()=>{ console.log('跳轉(zhuǎn)頁(yè)面') } },[]) returnIndex頁(yè)面
} function List(){ useEffect(()=>{ console.log(`useEffect=>List頁(yè)面`) }) returnList頁(yè)面
} function App5(){ const [count,setCount] = useState(0);//數(shù)組解構(gòu) return() } export default App5;You cliked {count} times
- 首頁(yè)
- list
}/> }/>
父子組件傳值useContext
useContext():共享狀態(tài)鉤子。作用就是可以做狀態(tài)的分發(fā),在React16.X以后支持,避免了react逐層通過(guò)Props傳遞數(shù)據(jù)。
使用步驟
1、先使用createContext創(chuàng)建上下文
2、然后使用Provider將值給提供出去
3、接收時(shí)用useContext接收就可以了
import React,{useState,createContext,useContext} from "react"; const CountContext = createContext(); function Counter(){ let count = useContext(CountContext); return ({count}
) } function App6(){ const [count,setCount] = useState(0);//數(shù)組解構(gòu) return() } export default App6;You cliked {count} times
useReducer
useReducer():Action鉤子
。在使用React的過(guò)程中,如遇到狀態(tài)管理,一般會(huì)用到Redux,而React本身是不提供狀態(tài)管理的。而useReducer()提供了狀態(tài)管理。首先,關(guān)于redux我們都知道,其原理是通過(guò)用戶在頁(yè)面中發(fā)起action,從而通過(guò)reducer方法來(lái)改變state,從而實(shí)現(xiàn)頁(yè)面和狀態(tài)的通信。而Reducer的形式是(state, action) => newstate
。
import React,{useReducer} from "react"; function Reduser(){ const [count,dispath] = useReducer((state,action)=>{ switch (action){ case "add": return state+1 case "sub": return state-1 default: return state } },0) return() } export default Reduser現(xiàn)在的分?jǐn)?shù)是{count}
原文鏈接:https://blog.csdn.net/shao_xuan_/article/details/123387287
相關(guān)推薦
- 2022-08-13 Linux新特性之btrfs文件系統(tǒng)
- 2021-12-12 簡(jiǎn)單介紹三層架構(gòu)工作原理_C#教程
- 2022-06-20 .NET?Core企業(yè)微信網(wǎng)頁(yè)授權(quán)登錄的實(shí)現(xiàn)_實(shí)用技巧
- 2022-03-11 Linux fatal error: iostream: No such file or direc
- 2022-07-13 Docker資源限制Cgroup
- 2022-05-04 Spring.Net框架簡(jiǎn)介_(kāi)實(shí)用技巧
- 2022-09-30 python實(shí)現(xiàn)圖像降噪_python
- 2022-10-06 react-router-dom入門(mén)使用教程(路由的模糊匹配與嚴(yán)格匹配)_React
- 最近更新
-
- 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)證過(guò)濾器
- Spring Security概述快速入門(mén)
- 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)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支