溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

react?hooks實(shí)現(xiàn)原理源碼分析

發(fā)布時(shí)間:2022-10-12 10:03:42 來源:億速云 閱讀:169 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下react hooks實(shí)現(xiàn)原理源碼分析的相關(guān)知識點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

react hooks 實(shí)現(xiàn)

Hooks 解決了什么問題

React 的設(shè)計(jì)哲學(xué)中,簡單的來說可以用下面這條公式來表示:

UI = f(data)

等號的左邊時(shí) UI 代表的最終畫出來的界面;等號的右邊是一個(gè)函數(shù),也就是我們寫的 React 相關(guān)的代碼;data 就是數(shù)據(jù),在 React 中,data 可以是 state 或者 props。
UI 就是把 data 作為參數(shù)傳遞給 f 運(yùn)算出來的結(jié)果。這個(gè)公式的含義就是,如果要渲染界面,不要直接去操縱 DOM 元素,而是修改數(shù)據(jù),由數(shù)據(jù)去驅(qū)動(dòng) React 來修改界面。
我們開發(fā)者要做的,就是設(shè)計(jì)出合理的數(shù)據(jù)模型,讓我們的代碼完全根據(jù)數(shù)據(jù)來描述界面應(yīng)該畫成什么樣子,而不必糾結(jié)如何去操作瀏覽器中的 DOM 樹結(jié)構(gòu)。

總體的設(shè)計(jì)原則:

  • 界面完全由數(shù)據(jù)驅(qū)動(dòng)

  • 一切皆組件

  • 使用 props 進(jìn)行組件之間通訊

與之帶來的問題有哪些呢?

  • 組件之間數(shù)據(jù)交流耦合度過高,許多組件之間需要共享的數(shù)據(jù)需要層層的傳遞;傳統(tǒng)的解決方式呢!

    • 變量提升

    • 高階函數(shù)透傳

    • 引入第三方數(shù)據(jù)管理庫,redux、mobx

    • 以上三種設(shè)計(jì)方式都是,都是將數(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)上面的問題都會(huì)迎刃而解

Hooks API 類型

據(jù)官方聲明,hooks 是完全向后兼容的,class componet 不會(huì)被移除,作為開發(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 是我們第一個(gè)接觸到 React Hooks,其主要作用是讓 Function Component 可以使用 state,接受一個(gè)參數(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,如果是一個(gè)狀態(tài)對應(yīng)不同類型更新處理,則可以使用 useReducer。

其次接觸到的是 Effect hooks

useEffect 的使用是讓 Function Componet 組件具備 life-cycles 聲明周期函數(shù);比如 componetDidMount、componetDidUpdate、shouldCompoentUpdate 以及 componetWiillunmount 都集中在這一個(gè)函數(shù)中執(zhí)行,叫 useEffect。這個(gè)函數(shù)有點(diǎn)類似 Redux 的 subscribe,會(huì)在每次 props、state 觸發(fā) render 之后執(zhí)行。(在組件第一次 render和每次 update 后觸發(fā))。

為什么叫 useEffect 呢?官方的解釋:因?yàn)槲覀兺ǔT谏芷趦?nèi)做很多操作都會(huì)產(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 時(shí)調(diào)用
      document.addEventListener('mousemove', handlerMouseCallback, false);

    return () => {
      // 在組件卸載之后執(zhí)行
        document.removeEventListener('mousemove', handlerMouseCallback, false);
    }
  })

  return client;
}

其中 useEffect 只是在組件首次 render 之后即 didMount 之后調(diào)用的,以及在組件卸載之時(shí)即 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 ,每次更新完之后,會(huì)賦值上一個(gè) update,方便 react 在渲染錯(cuò)誤的邊緣,數(shù)據(jù)回溯
  queue: UpdateQueue<any> | null,// UpdateQueue 通過
  next: Hook | null, // link 到下一個(gè) hooks,通過 next 串聯(lián)每一 hooks
}

type Effect = {
  tag: HookEffectTag, // effectTag 標(biāo)記當(dāng)前 hook 作用在 life-cycles 的哪一個(gè)階段
  create: () => mixed, // 初始化 callback
  destroy: (() => mixed) | null, // 卸載 callback
  deps: Array<mixed> | null,
  next: Effect, // 同上 
};

React Hooks 全局維護(hù)了一個(gè) workInProgressHook 變量,每一次調(diào)取 Hooks API 都會(huì)首先調(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];
}

react?hooks實(shí)現(xiàn)原理源碼分析

當(dāng)我們了解 React Hooks 的簡單原理,得到 Hooks 的串聯(lián)不是一個(gè)數(shù)組,但是是一個(gè)鏈?zhǔn)降臄?shù)據(jù)結(jié)構(gòu),從根節(jié)點(diǎn) workInProgressHook 向下通過 next 進(jìn)行串聯(lián)。這也就是為什么 Hooks 不能嵌套使用,不能在條件判斷中使用,不能在循環(huán)中使用。否則會(huì)破壞鏈?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)意會(huì)有此疑問,帶著這個(gè)疑問,閱讀一下源碼。

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 會(huì)綁定當(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);}

以上就是“react hooks實(shí)現(xiàn)原理源碼分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI