三分鐘搞懂react-hooks及實例代碼
背景
介紹Hooks之前,首先要說一下React的組件創(chuàng)建方式,一種是類組件,一種是純函數(shù)組件,并且React團隊希望,組件不要變成復雜的容器,最好只是數(shù)據(jù)流的管道。開發(fā)者根據(jù)需要,組合管道即可。也就是說組件的最佳寫法應該是函數(shù),而不是類。
但是我們知道,在以往開發(fā)中類組件和純函數(shù)組件的區(qū)別是很大的,純函數(shù)組件有著類組件不具備的多種特點:
純函數(shù)組件沒有狀態(tài)
純函數(shù)組件沒有生命周期
純函數(shù)組件沒有this
這就注定,我們所推崇的函數(shù)組件,只能做UI展示的功能,涉及到狀態(tài)的管理與切換,我們不得不用類組件或者redux,但我們知道類組件的也是有缺點的,比如,遇到簡單的頁面,代碼會顯得很重,并且每創(chuàng)建一個類組件,都要去繼承一個React實例;至于Redux,更不用多說,很久之前Redux的作者就說過,“能用React解決的問題就不用Redux”。
useState
useState():狀態(tài)鉤子。純函數(shù)組件沒有狀態(tài),useState()用于為函數(shù)組件引入狀態(tài)。
點擊加一效果,分別用類組件和函數(shù)組件實現(xiàn)??梢钥闯鲇胔ooks寫出的代碼更加精簡。
const [count,setCount] = useState(0);//數(shù)組解構,相當于下面三句話
let _useState = useState(0);
let count = _useState[0];
let setState = _useState[1]
類組件
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(
<div>
<p>you clicked {this.state.count} times</p>
<button onClick={this.addCount.bind(this)}>Click me</button>
</div>
)
}
}
export default App1;
函數(shù)組件
使用sueState重寫上面計數(shù)組件。
import React,{useState} from "react";
function App2(){
const [count,setCount] = useState(0);//數(shù)組解構
return(
<div>
<p>You cliked {count} times</p>
<button onClick={()=>{setCount(count+1)}}>Click me</button>
</div>
)
}
export default App2;

多狀態(tài)聲明
使用多條語句聲明不同的狀態(tài)
import React,{useState} from "react";
function App3(){
const [name,setName] = useState('劉備');//數(shù)組解構
const [age,setAge] = useState(25);
const [sex,setSex] = useState('男')
return(
<div>
<p>姓名:{name}</p>
<p>年齡:{age}</p>
<p>性別:{sex}</p>
</div>
)
}
export default App3;

useEffect
useEffect():副作用鉤子??梢杂脕砀玫奶幚砀弊饔茫绠惒秸埱蟮?,Hooks的useEffect()也是為函數(shù)組件提供了處理副作用的鉤子。在類組件中我們會把請求放在componentDidMount里面,在函數(shù)組件中我們可以使用useEffect()。
useEffect相當于componentDidMount和componentDidUpdate。
缺點:由于它是異步的因此不能實時處理。
類組件中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(
<div>
<p>you clicked {this.state.count} times</p>
<button onClick={this.addCount.bind(this)}>Click me</button>
</div>
)
}
}
export default App4;

useEffect模擬類組件中componentDidMount和componentDidUpdate
import React,{useState,useEffect} from "react";
function App5(){
const [count,setCount] = useState(0);//數(shù)組解構
useEffect(()=>{
console.log(`useEffect=>you clicked ${count} times`)
})
return(
<div>
<p>You cliked {count} times</p>
<button onClick={()=>{setCount(count+1)}}>Click me</button>
</div>
)
}
export default App5;

useEffect實現(xiàn)componmentWillUnment
先寫兩個路由跳轉頁面,并配置路由
import React,{useState,useEffect} from "react";
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom'
function Index(){
return <h2>Index頁面</h2>
}
function List(){
return <h2>List頁面</h2>
}
function App5(){
const [count,setCount] = useState(0);//數(shù)組解構
return(
<div>
<div>
<p>You cliked {count} times</p>
<button onClick={()=>{setCount(count+1)}}>Click me</button>
</div>
<Router>
<div>
<ul>
<li><Link to="/">首頁</Link></li>
<li><Link to="/list/">list</Link></li>
</ul>
<Routes>
<Route path="/" exact element={<Index/>}/>
<Route path="/list/" element={<List/>}/>
</Routes>
</div>
</Router>
</div>
)
}
export default App5;

使用useEffect表示進入頁面的狀態(tài)。
解綁時使用return,這時發(fā)現(xiàn)我們點擊按鈕時也會發(fā)生改變,這是因為只要組件發(fā)生改變,它就會觸發(fā)解綁。解決方法使用第二個參數(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頁面`)
return ()=>{
console.log('跳轉頁面')
}
})
return <h2>Index頁面</h2>
}
function List(){
useEffect(()=>{
console.log(`useEffect=>List頁面`)
})
return <h2>List頁面</h2>
}
function App5(){
const [count,setCount] = useState(0);//數(shù)組解構
return(
<div>
<div>
<p>You cliked {count} times</p>
<button onClick={()=>{setCount(count+1)}}>Click me</button>
</div>
<Router>
<div>
<ul>
<li><Link to="/">首頁</Link></li>
<li><Link to="/list/">list</Link></li>
</ul>
<Routes>
<Route path="/" exact element={<Index/>}/>
<Route path="/list/" element={<List/>}/>
</Routes>
</div>
</Router>
</div>
)
}
export default App5;

解綁限制,第二個參數(shù)是一個數(shù)組,如果數(shù)組為空表示頁面被銷毀觸發(fā),如果有變量,表示只有這個變量狀態(tài)變化才會觸發(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頁面`)
return ()=>{
console.log('跳轉頁面')
}
},[])
return <h2>Index頁面</h2>
}
function List(){
useEffect(()=>{
console.log(`useEffect=>List頁面`)
})
return <h2>List頁面</h2>
}
function App5(){
const [count,setCount] = useState(0);//數(shù)組解構
return(
<div>
<div>
<p>You cliked {count} times</p>
<button onClick={()=>{setCount(count+1)}}>Click me</button>
</div>
<Router>
<div>
<ul>
<li><Link to="/">首頁</Link></li>
<li><Link to="/list/">list</Link></li>
</ul>
<Routes>
<Route path="/" exact element={<Index/>}/>
<Route path="/list/" element={<List/>}/>
</Routes>
</div>
</Router>
</div>
)
}
export default App5;

父子組件傳值useContext
useContext():共享狀態(tài)鉤子。作用就是可以做狀態(tài)的分發(fā),在React16.X以后支持,避免了react逐層通過Props傳遞數(shù)據(jù)。
使用步驟
1、先使用createContext創(chuàng)建上下文
2、然后使用Provider將值給提供出去
3、接收時用useContext接收就可以了
import React,{useState,createContext,useContext} from "react";
const CountContext = createContext();
function Counter(){
let count = useContext(CountContext);
return (<h2>{count}</h2>)
}
function App6(){
const [count,setCount] = useState(0);//數(shù)組解構
return(
<div>
<p>You cliked {count} times</p>
<button onClick={()=>{setCount(count+1)}}>Click me</button>
<CountContext.Provider value={count}>
<Counter/>
</CountContext.Provider>
</div>
)
}
export default App6;

useReducer
useReducer():Action鉤子。在使用React的過程中,如遇到狀態(tài)管理,一般會用到Redux,而React本身是不提供狀態(tài)管理的。而useReducer()提供了狀態(tài)管理。首先,關于redux我們都知道,其原理是通過用戶在頁面中發(fā)起action,從而通過reducer方法來改變state,從而實現(xiàn)頁面和狀態(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(
<div>
<h2>現(xiàn)在的分數(shù)是{count}</h2>
<button onClick={()=>{dispath('add')}}>add</button>
<button onClick={()=>{dispath('sub')}}>sub</button>
</div>
)
}
export default Reduser

到此這篇關于三分鐘看完react-hooks的文章就介紹到這了,更多相關react hooks內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
react如何同步獲取useState的最新狀態(tài)值
這篇文章主要介紹了react如何同步獲取useState的最新狀態(tài)值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
用react-redux實現(xiàn)react組件之間數(shù)據(jù)共享的方法
這篇文章主要介紹了用react-redux實現(xiàn)react組件之間數(shù)據(jù)共享的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
React實現(xiàn)下拉框的key,value的值同時傳送
這篇文章主要介紹了React實現(xiàn)下拉框的key,value的值同時傳送方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
jsoneditor二次封裝實時預覽json編輯器組件react版
這篇文章主要為大家介紹了jsoneditor二次封裝實時預覽json編輯器組件react版示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
React Native中導航組件react-navigation跨tab路由處理詳解
這篇文章主要給大家介紹了關于React Native中導航組件react-navigation跨tab路由處理的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-10-10

