本文基于近段時(shí)間對(duì) hooks 碎片化的理解作一次簡(jiǎn)單梳理, 個(gè)人博客。同時(shí)歡迎關(guān)注基于 hooks 構(gòu)建的 UI 組件庫(kù) —— snake-design。
在 class 已經(jīng)融入 React 生態(tài)的節(jié)點(diǎn)下, React 推出的 Hooks 具有如下優(yōu)勢(shì):
- 更簡(jiǎn)潔的書(shū)寫(xiě);
- 相對(duì)類中的
HOC與render Props, Hooks 擁有更加自由地組合抽象的能力;
使用 Hooks 的注意項(xiàng)
-
在
hooks中每一次render都有自己的state和props, 這與class中存在差異, 見(jiàn) Hooks 每次渲染都是閉包 寫(xiě)出 useEffect 的所用到的依賴
在以下 demo 中, useEffect 的第二個(gè)參數(shù)傳入 [], 希望的是 useEffect 里的函數(shù)只執(zhí)行一次(類似在 componentDidMount 中執(zhí)行一次, 但是注意這里僅僅是類似, 詳細(xì)原因見(jiàn)上一條注意項(xiàng)), 頁(yè)面上每隔 1s 遞增 1。
function Demo() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => {
clearInterval(id);
};
}, []);
return count;
}
但這樣達(dá)到我們預(yù)期的效果了么? demo, 可以看到界面上只增加到 1 就停止了。原因就是傳入的第二個(gè)參數(shù) [] 搞的鬼, [] 表示沒(méi)有外界狀態(tài)對(duì) effect 產(chǎn)生干擾。流程大致如下:
- 第一次調(diào)用
useEffect傳入的count為 0, 于是setCount(0 + 1); - 受
useEffect第二個(gè)參數(shù)[]的影響,count仍然為 0, 所以相當(dāng)于還是setCount(0 + 1);
那如何修正上述問(wèn)題呢? 方法有兩個(gè)(方法一為主, 方法二為輔):
- 方法一: 將
[]改為[count] - 方法二: 將
setCount(count + 1)改為setCount(count => count + 1)。這種方法的思想是修正狀態(tài)的值而不依賴外面?zhèn)鬟M(jìn)的狀態(tài)。
不過(guò)遇到 setCount(count => count + 1) 的情況就可以考慮使用 useReducer 了。
何時(shí)使用 useReducer
使用 useState 的地方都能用 useReducer 進(jìn)行替代。相較 useState, useReducer 有如下優(yōu)勢(shì):
-
useReducer將how(reducer) 和what(dispatch(action)) 進(jìn)行抽離; 使用reducer邏輯狀態(tài)進(jìn)行集中化維護(hù); - 相比 useState, useReducer 沒(méi)有閉包問(wèn)題;
- 當(dāng)狀態(tài)的一個(gè) state 依賴狀態(tài)中的另一個(gè) state 時(shí), 這種情況最好使用 useReducer; 可以參考 decoupling-updates-from-actions 中 Dan 列舉的 demo。
處理 useEffect 中的公用函數(shù)
function Demo() {
const [count, setCount] = useState(0);
function getFetchUrl(query) {
return `http://demo${query}`
}
useEffect(() => {
const url = getFetchUrl('react')
}, [getFetchUrl]);
useEffect(() => {
const url = getFetchUrl('redux')
}, [getFetchUrl]);
return count;
}
此時(shí) useEffect 中傳入的第二個(gè)參數(shù) getFetchUrl 相當(dāng)于每次都是新的, 所以每次都會(huì)請(qǐng)求數(shù)據(jù), 那除了 [getFetchUrl] 將改為 [] 這種不推薦的寫(xiě)法外,有兩種解決方法:
*. 方法一: 提升 getFetchUrl 的作用域;
*. 方法二: 使用 useCallback 或者 useMemo 來(lái)包裹 getFetchUrl;
React.memo修飾一個(gè)函數(shù)組件,useMemo修飾一個(gè)函數(shù)。它們本質(zhì)都是運(yùn)用緩存。
React Hooks 內(nèi)部是怎么工作的
為了理解 React Hooks 內(nèi)部實(shí)現(xiàn)原理, 對(duì) useState、useEffect 進(jìn)行了簡(jiǎn)單的實(shí)現(xiàn)。
useState 的簡(jiǎn)單實(shí)現(xiàn)
使用閉包來(lái)實(shí)現(xiàn) useState 的簡(jiǎn)單邏輯:
// 這里使用閉包
const React = (function() {
let _val
return {
useState(initialValue) {
_val = _val || initialValue
function setVal(value) {
_val = value
}
return [_val, setVal]
}
}
})()
測(cè)試如下:
function Counter() {
const [count, setCount] = React.useState(0)
return {
render: () => console.log(count),
click: () => setCount(count + 1)
}
}
Counter().render() // 0
Counter().click() // 模擬點(diǎn)擊
Counter().render() // 1
useEffect 的簡(jiǎn)單實(shí)現(xiàn)
var React = (function() {
let _val, _deps
return {
useState(initialValue) {
_val = _val || initialValue
function setVal(value) {
_val = value
}
return [_val, setVal]
},
useEffect(callback, deps) {
const ifUpdate = !deps
// 判斷 Deps 中的依賴是否改變
const ifDepsChange = _deps ? !_deps.every((r, index) => r === deps[index]) : true
if (ifUpdate || ifDepsChange) {
callback()
_deps = deps || []
}
}
}
})()
測(cè)試代碼如下:
var {useState, useEffect} = React
function Counter() {
const [count, setCount] = useState(0)
useEffect(() => {
console.log('useEffect', count)
}, [count])
return {
render: () => console.log('render', count),
click: () => setCount(count + 1),
noop: () => setCount(count), // 保持不變, 觀察 useEffect 是否被調(diào)用
}
}
Counter().render() // 'useEffect' 0, 'render', 0
Counter().noop()
Counter().render() // 'render', 0
Counter().click()
Counter().render() // 'useEffect' 1, 'render', 1
處理多次調(diào)用的情形
為了在 hooks 中能使用多次 useState, useEffect, 將各個(gè) useState, useEffect 的調(diào)用存進(jìn)一個(gè)數(shù)組中, 在上面基礎(chǔ)上進(jìn)行如下改造:
const React = (function() {
const hooks = []
let currentHook = 0
return {
render(Component) {
const component = Component()
component.render()
currentHook = 0 // 重置, 這里很關(guān)鍵, 將 hooks 的執(zhí)行放到 hooks 隊(duì)列中, 確保每次執(zhí)行的順序保持一致。
return component
},
useState(initialValue) {
hooks[currentHook] = hooks[currentHook] || initialValue
function setVal(value) {
hooks[currentHook] = value
}
return [hooks[currentHook++], setVal]
},
useEffect(callback, deps) {
const ifUpdate = !deps
// 判斷 Deps 中的依賴是否改變
const ifDepsChange = hooks[currentHook] ? !hooks[currentHook].every((r, index) => r === deps[index]) : true
if (ifUpdate || ifDepsChange) {
callback()
hooks[currentHook++] = deps || []
}
}
}
})()
測(cè)試代碼如下:
var {useState, useEffect} = React
function Counter() {
const [count, setCount] = useState(0)
const [type, setType] = useState('hi')
useEffect(() => {
console.log('useEffect', count)
console.log('type', type)
}, [count, type])
return {
render: () => console.log('render', count),
click: () => setCount(count + 1),
noop: () => setCount(count), // 保持不變, 觀察 useEffect 是否被調(diào)用
}
}
/* 如下 mock 執(zhí)行了 useEffect、render; 這里使用 React.render 的原因是為了重置 currentHook 的值 */
let comp = React.render(Counter) // useEffect 0 type hi render 0
/* 如下 mock 只執(zhí)行了 render */
comp.noop()
comp = React.render(Counter) // render 0
/* 如下 mock 重新執(zhí)行了 useEffect、render */
comp.click()
React.render(Counter) // useEffect 1, render 1