关于react.js:深度探讨reacthooks实现原理

4次阅读

共计 6408 个字符,预计需要花费 17 分钟才能阅读完成。

react hooks 实现

Hooks 解决了什么问题

React 的设计哲学中,简略的来说能够用上面这条公式来示意:

UI = f(data)

等号的右边时 UI 代表的最终画进去的界面;等号的左边是一个函数,也就是咱们写的 React 相干的代码;data 就是数据,在 React 中,data 能够是 state 或者 props。
UI 就是把 data 作为参数传递给 f 运算进去的后果。这个公式的含意就是,如果要渲染界面,不要间接去操纵 DOM 元素,而是批改数据,由数据去驱动 React 来批改界面。
咱们开发者要做的,就是设计出正当的数据模型,让咱们的代码齐全依据数据来形容界面应该画成什么样子,而不用纠结如何去操作浏览器中的 DOM 树结构。

总体的设计准则:

  • 界面齐全由数据驱动
  • 所有皆组件
  • 应用 props 进行组件之间通信

与之带来的问题有哪些呢?

  • 组件之间数据交换耦合度过高,许多组件之间须要共享的数据须要层层的传递;传统的解决形式呢!

    • 变量晋升
    • 高阶函数透传
    • 引入第三方数据管理库,redux、mobx
    • 以上三种设计形式都是,都是将数据晋升至父节点或者最高节点,而后数据层层传递
  • ClassComponet 生命周期的学习老本,以及强关联的代码逻辑因为生命周期钩子函数的执行过程,须要将代码进行强行拆分;常见的:
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 的呈现下面的问题都会迎刃而解

Hooks API 类型

据官网申明,hooks 是齐全向后兼容的,class componet 不会被移除,作为开发者能够缓缓迁徙到最新的 API。

Hooks 次要分三种:

  • State hooks : 能够让 function componet 应用 state
  • Effect hooks : 能够让 function componet 应用生命周期和 side effect
  • Custom hooks: 依据 react 提供的 useState、useReducer、useEffect、useRef 等自定义本人须要的 hooks

上面咱们来理解一下 Hooks。

首先接触到的是 State hooks

useState 是咱们第一个接触到 React Hooks,其次要作用是让 Function Component 能够应用 state,承受一个参数做为 state 的初始值,返回以后的 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>
}

与之对应的 hooks 还有 useReducer,如果是一个状态对应不同类型更新解决,则能够应用 useReducer。

其次接触到的是 Effect hooks

useEffect 的应用是让 Function Componet 组件具备 life-cycles 申明周期函数;比方 componetDidMount、componetDidUpdate、shouldCompoentUpdate 以及 componetWiillunmount 都集中在这一个函数中执行,叫 useEffect。这个函数有点相似 Redux 的 subscribe,会在每次 props、state 触发 render 之后执行。( 在组件第一次 render 和每次 update 后触发 )。

为什么叫 useEffect 呢?官网的解释:因为咱们通常在生命周期内做很多操作都会产生一些 side-effect (副作用) 的操作,比方更新 DOM,fetch 数据等。

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 时调用
      document.addEventListener('mousemove', handlerMouseCallback, false);

    return () => {
      // 在组件卸载之后执行
        document.removeEventListener('mousemove', handlerMouseCallback, false);
    }
  })

  return client;
}

其中 useEffect 只是在组件首次 render 之后即 didMount 之后调用的,以及在组件卸载之时即 unmount 之后调用,如果须要在 DOM 更新之后同步执行,能够应用 useLayoutEffect。

最初接触到的是 custom hooks

依据官网提供的 useXXX API 联合本人的业务场景,能够应用自定义开发须要的 custom hooks,从而抽离业务开发数据,按需引入;实现业务数据与视图数据的充沛解耦。

Hooks 实现形式

在下面的根底之后,对于 hooks 的应用应该有了根本的理解,上面咱们联合 hooks 源码对于 hooks 如何能保留无状态组件的原理进行剥离。

Hooks 源码在 Reactreact-reconclier** 中的 ReactFiberHooks.js,代码有 600 行,了解起来也是很不便的

Hooks 的根本类型:

type Hooks = {
    memoizedState: any, // 指向以后渲染节点 Fiber
  baseState: any, // 初始化 initialState,曾经每次 dispatch 之后 newState
  baseUpdate: Update<any> | null,// 以后须要更新的 Update,每次更新完之后,会赋值上一个 update,不便 react 在渲染谬误的边缘,数据回溯
  queue: UpdateQueue<any> | null,// UpdateQueue 通过
  next: Hook | null, // link 到下一个 hooks,通过 next 串联每一 hooks
}

type Effect = {
  tag: HookEffectTag, // effectTag 标记以后 hook 作用在 life-cycles 的哪一个阶段
  create: () => mixed, // 初始化 callback
  destroy: (() => mixed) | null, // 卸载 callback
  deps: Array<mixed> | null,
  next: Effect, // 同上 
};

React Hooks 全局保护了一个 workInProgressHook 变量,每一次调取 Hooks API 都会首先调取 createWorkInProgressHooks 函数。参考 React 实战视频解说:进入学习

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;
}

假如咱们须要执行以下 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 的简略原理,失去 Hooks 的串联不是一个数组,然而是一个链式的数据结构,从根节点 workInProgressHook 向下通过 next 进行串联。 这也就是为什么 Hooks 不能嵌套应用,不能在条件判断中应用,不能在循环中应用。否则会毁坏链式构造。

问题一:useState dispatch 函数如何与其应用的 Function Component 进行绑定

上面咱们先看一段代码:

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 的能力,然而对于开发者来讲,只有在 Function Component 中引入了 hooks 函数,dispatch 之后就可能作用就能精确的作用在以后的组件上,不经意会有此疑难,带着这个疑难,浏览一下源码。

function useState(initialState){  return useReducer(basicStateReducer,    // useReducer has a special case to support lazy useState initializers    (initialState: any),  );}function useReducer(reducer, initialState, initialAction) {  // 解析以后正在 rendering 的 Fiber
    let fiber = (currentlyRenderingFiber = resolveCurrentlyRenderingFiber());  workInProgressHook = createWorkInProgressHook();  // 此处省略局部源码  ...  ...  ...  // dispathAction 会绑定以后真在渲染的 Fiber,重点在 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);}
正文完
 0