react hooks實(shí)現(xiàn)原理解析
react hooks 實(shí)現(xiàn)
Hooks 解決了什么問題
在 React 的設(shè)計哲學(xué)中,簡單的來說可以用下面這條公式來表示:
UI = f(data)
等號的左邊時 UI 代表的最終畫出來的界面;等號的右邊是一個函數(shù),也就是我們寫的 React 相關(guān)的代碼;data 就是數(shù)據(jù),在 React 中,data 可以是 state 或者 props。
UI 就是把 data 作為參數(shù)傳遞給 f 運(yùn)算出來的結(jié)果。這個公式的含義就是,如果要渲染界面,不要直接去操縱 DOM 元素,而是修改數(shù)據(jù),由數(shù)據(jù)去驅(qū)動 React 來修改界面。
我們開發(fā)者要做的,就是設(shè)計出合理的數(shù)據(jù)模型,讓我們的代碼完全根據(jù)數(shù)據(jù)來描述界面應(yīng)該畫成什么樣子,而不必糾結(jié)如何去操作瀏覽器中的 DOM 樹結(jié)構(gòu)。
總體的設(shè)計原則:
- 界面完全由數(shù)據(jù)驅(qū)動
- 一切皆組件
- 使用 props 進(jìn)行組件之間通訊
與之帶來的問題有哪些呢?
- 組件之間數(shù)據(jù)交流耦合度過高,許多組件之間需要共享的數(shù)據(jù)需要層層的傳遞;傳統(tǒng)的解決方式呢!
- 變量提升
- 高階函數(shù)透傳
- 引入第三方數(shù)據(jù)管理庫,redux、mobx
- 以上三種設(shè)計方式都是,都是將數(shù)據(jù)提升至父節(jié)點(diǎn)或者最高節(jié)點(diǎn),然后數(shù)據(jù)層層傳遞
- ClassComponet 生命周期的學(xué)習(xí)成本,以及強(qiáng)關(guān)聯(lián)的代碼邏輯由于生命周期鉤子函數(shù)的執(zhí)行過程,需要將代碼進(jìn)行強(qiáng)行拆分;常見的:
class SomeCompoent extends Component {
componetDidMount() {
const node = this.refs['myRef'];
node.addEventListener('mouseDown', handlerMouseDown);
node.addEventListener('mouseUp', handlerMouseUp)
}
...
componetWillunmount() {
const node = this.refs['myRef'];
node.removeEventListener('mouseDown', handlerMouseDown)
node.removeEventListener('mouseUp', handlerMouseUp)
}
}可以說 Hooks 的出現(xiàn)上面的問題都會迎刃而解
Hooks API 類型
據(jù)官方聲明,hooks 是完全向后兼容的,class componet 不會被移除,作為開發(fā)者可以慢慢遷移到最新的 API。
Hooks 主要分三種:
- State hooks : 可以讓 function componet 使用 state
- Effect hooks : 可以讓 function componet 使用生命周期和 side effect
- Custom hooks: 根據(jù) react 提供的 useState、useReducer、useEffect、useRef等自定義自己需要的 hooks
下面我們來了解一下 Hooks。
首先接觸到的是 State hooks
useState 是我們第一個接觸到 React Hooks,其主要作用是讓 Function Component 可以使用 state,接受一個參數(shù)做為 state 的初始值,返回當(dāng)前的 state 和 dispatch。
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
</div>
);
}
其中 useState 可以多次聲明;
function FunctionalComponent () {
const [state1, setState1] = useState(1)
const [state2, setState2] = useState(2)
const [state3, setState3] = useState(3)
return <div>{state1}{...}</div>
}與之對應(yīng)的 hooks 還有 useReducer,如果是一個狀態(tài)對應(yīng)不同類型更新處理,則可以使用 useReducer。
其次接觸到的是 Effect hooks
useEffect 的使用是讓 Function Componet 組件具備 life-cycles 聲明周期函數(shù);比如 componetDidMount、componetDidUpdate、shouldCompoentUpdate 以及 componetWiillunmount 都集中在這一個函數(shù)中執(zhí)行,叫 useEffect。這個函數(shù)有點(diǎn)類似 Redux 的 subscribe,會在每次 props、state 觸發(fā) render 之后執(zhí)行。(在組件第一次 render和每次 update 后觸發(fā))。
為什么叫 useEffect 呢?官方的解釋:因?yàn)槲覀兺ǔT谏芷趦?nèi)做很多操作都會產(chǎn)生一些 side-effect (副作用) 的操作,比如更新 DOM,fetch 數(shù)據(jù)等。
useEffect 是使用:
import React, { useState, useEffect } from 'react';
function useMousemove() {
const [client, setClient] = useState({x: 0, y: 0});
useEffect(() => {
const handlerMouseCallback = (e) => {
setClient({
x: e.clientX,
y: e.clientY
})
};
// 在組件首次 render 之后, 既在 didMount 時調(diào)用
document.addEventListener('mousemove', handlerMouseCallback, false);
return () => {
// 在組件卸載之后執(zhí)行
document.removeEventListener('mousemove', handlerMouseCallback, false);
}
})
return client;
}其中 useEffect 只是在組件首次 render 之后即 didMount 之后調(diào)用的,以及在組件卸載之時即 unmount 之后調(diào)用,如果需要在 DOM 更新之后同步執(zhí)行,可以使用 useLayoutEffect。
最后接觸到的是 custom hooks
根據(jù)官方提供的 useXXX API 結(jié)合自己的業(yè)務(wù)場景,可以使用自定義開發(fā)需要的 custom hooks,從而抽離業(yè)務(wù)開發(fā)數(shù)據(jù),按需引入;實(shí)現(xiàn)業(yè)務(wù)數(shù)據(jù)與視圖數(shù)據(jù)的充分解耦。
Hooks 實(shí)現(xiàn)方式
在上面的基礎(chǔ)之后,對于 hooks 的使用應(yīng)該有了基本的了解,下面我們結(jié)合 hooks 源碼對于 hooks 如何能保存無狀態(tài)組件的原理進(jìn)行剝離。
Hooks 源碼在 Reactreact-reconclier** 中的 ReactFiberHooks.js ,代碼有 600 行,理解起來也是很方便的
Hooks 的基本類型:
type Hooks = {
memoizedState: any, // 指向當(dāng)前渲染節(jié)點(diǎn) Fiber
baseState: any, // 初始化 initialState, 已經(jīng)每次 dispatch 之后 newState
baseUpdate: Update<any> | null,// 當(dāng)前需要更新的 Update ,每次更新完之后,會賦值上一個 update,方便 react 在渲染錯誤的邊緣,數(shù)據(jù)回溯
queue: UpdateQueue<any> | null,// UpdateQueue 通過
next: Hook | null, // link 到下一個 hooks,通過 next 串聯(lián)每一 hooks
}
type Effect = {
tag: HookEffectTag, // effectTag 標(biāo)記當(dāng)前 hook 作用在 life-cycles 的哪一個階段
create: () => mixed, // 初始化 callback
destroy: (() => mixed) | null, // 卸載 callback
deps: Array<mixed> | null,
next: Effect, // 同上
};React Hooks 全局維護(hù)了一個 workInProgressHook 變量,每一次調(diào)取 Hooks API 都會首先調(diào)取 createWorkInProgressHooks 函數(shù)。參考React實(shí)戰(zhàn)視頻講解:進(jìn)入學(xué)習(xí)
function createWorkInProgressHook() {
if (workInProgressHook === null) {
// This is the first hook in the list
if (firstWorkInProgressHook === null) {
currentHook = firstCurrentHook;
if (currentHook === null) {
// This is a newly mounted hook
workInProgressHook = createHook();
} else {
// Clone the current hook. workInProgressHook = cloneHook(currentHook);
}
firstWorkInProgressHook = workInProgressHook;
} else {
// There's already a work-in-progress. Reuse it. currentHook = firstCurrentHook;
workInProgressHook = firstWorkInProgressHook;
}
} else {
if (workInProgressHook.next === null) {
let hook;
if (currentHook === null) {
// This is a newly mounted hook
hook = createHook();
} else {
currentHook = currentHook.next;
if (currentHook === null) {
// This is a newly mounted hook
hook = createHook();
} else {
// Clone the current hook. hook = cloneHook(currentHook);
}
}
// Append to the end of the list
workInProgressHook = workInProgressHook.next = hook;
} else {
// There's already a work-in-progress. Reuse it. workInProgressHook = workInProgressHook.next;
currentHook = currentHook !== null ? currentHook.next : null;
}
}
return workInProgressHook;
}假設(shè)我們需要執(zhí)行以下 hooks 代碼:
function FunctionComponet() {
const [ state0, setState0 ] = useState(0);
const [ state1, setState1 ] = useState(1);
useEffect(() => {
document.addEventListener('mousemove', handlerMouseMove, false);
...
...
...
return () => {
...
...
...
document.removeEventListener('mousemove', handlerMouseMove, false);
}
})
const [ satte3, setState3 ] = useState(3);
return [state0, state1, state3];
}
當(dāng)我們了解 React Hooks 的簡單原理,得到 Hooks 的串聯(lián)不是一個數(shù)組,但是是一個鏈?zhǔn)降臄?shù)據(jù)結(jié)構(gòu),從根節(jié)點(diǎn) workInProgressHook 向下通過 next 進(jìn)行串聯(lián)。這也就是為什么 Hooks 不能嵌套使用,不能在條件判斷中使用,不能在循環(huán)中使用。否則會破壞鏈?zhǔn)浇Y(jié)構(gòu)。
問題一:useState dispatch 函數(shù)如何與其使用的 Function Component 進(jìn)行綁定
下面我們先看一段代碼:
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
const useWindowSize = () => {
let [size, setSize] = useState([window.innerWidth, window.innerHeight])
useEffect(() => {
let handleWindowResize = event => {
setSize([window.innerWidth, window.innerHeight])
}
window.addEventListener('resize', handleWindowResize)
return () => window.removeEventListener('resize', handleWindowResize)
}, [])
return size
}
const App = () => {
const [ innerWidth, innerHeight ] = useWindowSize();
return (
<ul>
<li>innerWidth: {innerWidth}</li>
<li>innerHeight: {innerHeight}</li>
</ul>
)
}
ReactDOM.render(<App/>, document.getElementById('root'))useState 的作用是讓 Function Component 具備 State 的能力,但是對于開發(fā)者來講,只要在 Function Component 中引入了 hooks 函數(shù),dispatch 之后就能夠作用就能準(zhǔn)確的作用在當(dāng)前的組件上,不經(jīng)意會有此疑問,帶著這個疑問,閱讀一下源碼。
function useState(initialState){ return useReducer(
basicStateReducer, // useReducer has a special case to support lazy useState initializers (initialState: any), );}function useReducer(reducer, initialState, initialAction) { // 解析當(dāng)前正在 rendering 的 Fiber
let fiber = (currentlyRenderingFiber = resolveCurrentlyRenderingFiber()); workInProgressHook = createWorkInProgressHook(); // 此處省略部分源碼 ... ... ... // dispathAction 會綁定當(dāng)前真在渲染的 Fiber, 重點(diǎn)在 dispatchAction 中 const dispatch = dispatchAction.bind(null, currentlyRenderingFiber,queue,) return [workInProgressHook.memoizedState, dispatch];}function dispatchAction(fiber, queue, action) { const alternate = fiber.alternate; const update: Update<S, A> = { expirationTime, action, eagerReducer: null, eagerState: null, next: null, }; ...... ...... ...... scheduleWork(fiber, expirationTime);}
到此這篇關(guān)于react hooks實(shí)現(xiàn)原理的文章就介紹到這了,更多相關(guān)react hooks原理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React Native自定義標(biāo)題欄組件的實(shí)現(xiàn)方法
今天講一下如何實(shí)現(xiàn)自定義標(biāo)題欄組件,我們都知道RN有一個優(yōu)點(diǎn)就是可以組件化,在需要使用該組件的地方直接引用并傳遞一些參數(shù)就可以了,這種方式確實(shí)提高了開發(fā)效率。對React Native自定義標(biāo)題欄組件的實(shí)現(xiàn)方法感興趣的朋友參考下2017-01-01
2023年最新react面試題總結(jié)大全(附詳細(xì)答案)
React是一種廣泛使用的JavaScript庫,為構(gòu)建用戶界面提供了強(qiáng)大的工具和技術(shù),這篇文章主要給大家介紹了關(guān)于2023年最新react面試題的相關(guān)資料,文中還附有詳細(xì)答案,需要的朋友可以參考下2023-10-10
React18從0實(shí)現(xiàn)dispatch?update流程
這篇文章主要為大家介紹了React18從0實(shí)現(xiàn)dispatch?update流程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
教你應(yīng)用?SOLID?原則整理?React?代碼之單一原則
這篇文章主要介紹了如何應(yīng)用?SOLID?原則整理?React?代碼之單一原則,今天,我們將從一個糟糕的代碼示例開始,應(yīng)用 SOLID 的第一個原則,看看它如何幫助我們編寫小巧、漂亮、干凈的并明確責(zé)任的 React 組件,需要的朋友可以參考下2022-07-07
TypeScript在React中的應(yīng)用技術(shù)實(shí)例解析
這篇文章主要為大家介紹了TypeScript在React中的應(yīng)用技術(shù)實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

