[前端] React深入浅出分析Hooks源码

1983 0
黑夜隐士 2022-11-8 09:09:50 | 显示全部楼层 |阅读模式
目录

    useState 解析
      useState 使用useState 模拟实现hooks 规则
    useEffect 解析
      useEffect 使用useEffect 的模拟实现useEffect 注意事项接口无限请求问题
    Hooks 源码解析总结


useState 解析


useState 使用

通常我们这样来使用 useState 方法
  1. function App() {
  2.   const [num, setNum] = useState(0);
  3.   const add = () => {
  4.     setNum(num + 1);
  5.   };
  6.   return (
  7.     <div>
  8.       <p>数字: {num}</p>
  9.      <button onClick={add}> +1 </button>
  10.     </div>
  11.   );
  12. }
复制代码
useState 的使用过程,我们先模拟一个大概的函数
  1. function useState(initialValue) {
  2.   var value = initialValue
  3.   function setState(newVal) {   
  4.     value = newVal
  5.   }
  6.   return [value, setState]
  7. }
复制代码
这个代码有一个问题,在执行 useState 的时候每次都会 var _val = initialValue,初始化数据;
于是我们可以用闭包的形式来保存状态。
  1. const MyReact = (function() {
  2.    // 定义一个 value 保存在该模块的全局中
  3.   let value
  4.   return {
  5.     useState(initialValue) {
  6.       value = value || initialValue
  7.       function setState(newVal) {
  8.         value = newVal
  9.       }
  10.       return [value, setState]
  11.     }
  12.   }
  13. })()
复制代码
这样在每次执行的时候,就能够通过闭包的形式 来保存 value。
不过这个还是不符合 react 中的 useState。因为在实际操作中会出现多次调用,如下。
  1. function App() {
  2.   const [name, setName] = useState('Kevin');
  3.   const [age, setAge] = useState(0);
  4.   const handleName = () => {
  5.     setNum('Dom');
  6.   };
  7.   const handleAge = () => {
  8.     setAge(age + 1);
  9.   };
  10.   return (
  11.     <div>
  12.       <p>姓名: {name}</p>
  13.       <button onClick={handleName}> 改名字 </button>
  14.        <p>年龄: {age}</p>
  15.       <button onClick={handleAge}> 加一岁 </button>
  16.     </div>
  17.   );
  18. }
复制代码
因此我们需要在改变 useState 储存状态的方式

useState 模拟实现
  1. const MyReact = (function() {
  2.   // 开辟一个储存 hooks 的空间
  3.   let hooks = [];
  4.   // 指针从 0 开始
  5.   let currentHook = 0
  6.   return {
  7.     // 伪代码 解释重新渲染的时候 会初始化 currentHook
  8.     render(Component) {
  9.       const Comp = Component()
  10.       Comp.render()
  11.       currentHook = 0 // 重新渲染时候改变 hooks 指针
  12.       return Comp
  13.     },      
  14.     useState(initialValue) {
  15.       hooks[currentHook] = hooks[currentHook] || initialValue
  16.       const setStateHookIndex = currentHook
  17.       // 这里我们暂且默认 setState 方式第一个参数不传 函数,直接传状态
  18.       const setState = newState => (hooks[setStateHookIndex] = newState)
  19.       return [hooks[currentHook++], setState]
  20.     }
  21.   }
  22. })()
复制代码
因此当重新渲染 App 的时候,再次执行 useState 的时候传入的参数 kevin , 0 也就不会去使用,而是直接拿之前 hooks 存储好的值。

hooks 规则

官网 hoos 规则中明确的提出 hooks 不要再循环,条件或嵌套函数中使用。


为什么不可以?
我们来看下
下面这样一段代码。执行 useState 重新渲染,和初始化渲染 顺序不一样就会出现如下问题
如果了解了上面 useState 模拟写法的存储方式,那么这个问题的原因就迎刃而解了。相关参考视频:传送门





useEffect 解析


useEffect 使用

初始化会 打印一次 ‘useEffect_execute’, 改变年龄重新render,会再打印, 改变名字重新 render, 不会打印。因为依赖数组里面就监听了 age 的值
  1. import React, { useState, useEffect } from 'react';
  2. function App() {
  3.   const [name, setName] = useState('Kevin');
  4.   const [age, setAge] = useState(0);
  5.   const handleName = () => {
  6.     setName('Don');
  7.   };
  8.   const handleAge = () => {
  9.     setAge(age + 1);
  10.   };
  11.   useEffect(()=>{
  12.     console.log('useEffect_execute')
  13.   }, [age])
  14.   return (
  15.     <div>
  16.       <p>姓名: {name}</p>
  17.       <button onClick={handleName}> 改名字 </button>
  18.       <p>年龄: {age}</p>
  19.       <button onClick={handleAge}> 加一岁 </button>
  20.     </div>
  21.   );
  22. }
  23. export default App;
复制代码
useEffect 的模拟实现
  1. const MyReact = (function() {
  2.   // 开辟一个储存 hooks 的空间
  3.   let hooks = [];
  4.   // 指针从 0 开始
  5.   let currentHook = 0 ;
  6.   // 定义个模块全局的 useEffect 依赖
  7.   let deps;
  8.   return {
  9.     // 伪代码 解释重新渲染的时候 会初始化 currentHook
  10.     render(Component) {
  11.       const Comp = Component()
  12.       Comp.render()
  13.       currentHook = 0 // 重新渲染时候改变 hooks 指针
  14.       return Comp
  15.     },      
  16.     useState(initialValue) {
  17.       hooks[currentHook] = hooks[currentHook] || initialValue
  18.       const setStateHookIndex = currentHook
  19.       // 这里我们暂且默认 setState 方式第一个参数不传 函数,直接传状态
  20.       const setState = newState => (hooks[setStateHookIndex] = newState)
  21.       return [hooks[currentHook++], setState]
  22.     }
  23.     useEffect(callback, depArray) {
  24.       const hasNoDeps = !depArray
  25.       // 如果没有依赖,说明是第一次渲染,或者是没有传入依赖参数,那么就 为 true
  26.       // 有依赖 使用 every 遍历依赖的状态是否变化, 变化就会 true
  27.       const hasChangedDeps = deps ? !depArray.every((el, i) => el === deps[i]) : true
  28.       // 如果没有依赖, 或者依赖改变
  29.       if (hasNoDeps || hasChangedDeps) {
  30.         // 执行
  31.         callback()
  32.         // 更新依赖
  33.         deps = depArray
  34.       }
  35.     },
  36.   }
  37. })()
复制代码
useEffect 注意事项

依赖项要真实
依赖需要想清楚。
刚开始使用 useEffect 的时候,我只有想重新触发 useEffect 的时候才会去设置依赖
那么也就会出现如下的问题。
希望的效果是界面中一秒增加一岁
  1. import React, { useState, useEffect } from 'react';
  2. function App() {
  3.   const [name, setName] = useState('Kevin');
  4.   const [age, setAge] = useState(0);
  5.   const handleName = () => {
  6.     setName('Don');
  7.   };
  8.   const handleAge = () => {
  9.     setAge(age + 1);
  10.   };
  11.   useEffect(() => {
  12.     setInterval(() => {
  13.       setAge(age + 1);
  14.       console.log(age)
  15.     }, 1000);
  16.   }, []);
  17.   return (
  18.     <div>
  19.       <p>姓名: {name}</p>
  20.       <button onClick={handleName}> 改名字 </button>
  21.       <p>年龄: {age}</p>
  22.       <button onClick={handleAge}> 加一岁 </button>
  23.     </div>
  24.   );
  25. }
  26. export default App;
复制代码
其实你会发现 这里界面就增加了 一次 年龄。究其原因:
**在第一次渲染中,age是0。因此,setAge(age+ 1)在第一次渲染中等价于setAge(0 + 1)。然而我设置了0依赖为空数组,那么之后的 useEffect 不会再重新运行,它后面每一秒都会调用setAge(0 + 1) **
也就是当我们需要 依赖 age 的时候我们 就必须再 依赖数组中去记录他的依赖。这样useEffect 才会正常的给我们去运行。
所以我们想要每秒都递增的话有两种方法
方法一:
真真切切的把你所依赖的状态填写到 数组中
  1.   // 通过监听 age 的变化。来重新执行 useEffect 内的函数
  2.   // 因此这里也就需要记录定时器,当卸载的时候我们去清空定时器,防止多个定时器重新触发
  3.   useEffect(() => {
  4.     const id = setInterval(() => {
  5.       setAge(age + 1);
  6.     }, 1000);
  7.     return () => {
  8.       clearInterval(id)
  9.     };
  10.   }, [age]);
复制代码
方法二
useState 的参数传入 一个方法。
注:上面我们模拟的 useState 并没有做这个处理 后面我会讲解源码中去解析。
  1. useEffect(() => {
  2.     setInterval(() => {
  3.       setAge(age => age + 1);
  4.     }, 1000);
  5.   }, []);
复制代码
useEffect 只运行了一次,通过 useState 传入函数的方式它不再需要知道当前的age值。因为 React render 的时候它会帮我们处理
这正是setAge(age => age + 1)做的事情。再重新渲染的时候他会帮我们执行这个方法,并且传入最新的状态。
所以我们做到了去时刻改变状态,但是依赖中却不用写这个依赖,因为我们将原本的使用到的依赖移除了。(这句话表达感觉不到位)

接口无限请求问题

刚开始使用 useEffect 的我,在接口请求的时候常常会这样去写代码。
props 里面有 页码,通过切换页码,希望监听页码的变化来重新去请求数据
  1. // 以下是伪代码
  2. // 这里用 dva 发送请求来模拟
  3. import React, { useState, useEffect } from 'react';
  4. import { connect } from 'dva';
  5. function App(props) {
  6.   const { goods, dispatch, page } = props;
  7.   useEffect(() => {
  8.     // 页面完成去发情请求
  9.    dispatch({
  10.       type: '/goods/list',
  11.       payload: {page, pageSize:10},
  12.     });
  13.     // xxxx
  14.   }, [props]);
  15.   return (
  16.     <div>
  17.       <p>商品: {goods}</p>
  18.      <button>点击切下一页</button>
  19.     </div>
  20.   );
  21. }
  22. export default connect(({ goods }) => ({
  23.   goods,
  24. }))(App);
复制代码
然后得意洋洋的刷新界面,发现 Network 中疯狂循环的请求接口,导致页面的卡死。
究其原因是因为在依赖中,我们通过接口改变了状态 props 的更新, 导致重新渲染组件,导致会重新执行 useEffect 里面的方法,方法执行完成之后 props 的更新, 导致重新渲染组件,依赖项目是对象,引用类型发现不相等,又去执行 useEffect 里面的方法,又重新渲染,然后又对比,又不相等, 又执行。因此产生了无限循环。

Hooks 源码解析

该源码位置: react/packages/react-reconciler/src/ReactFiberHooks.js
  1. const Dispatcher={
  2.   useReducer: mountReducer,
  3.   useState: mountState,
  4.   // xxx 省略其他的方法
  5. }
复制代码
mountState 源码
  1. function mountState<S>(
  2.   initialState: (() => S) | S,
  3. ): [S, Dispatch<BasicStateAction<S>>] {
  4.     /*    mountWorkInProgressHook 方法 返回初始化对象    {        memoizedState: null,        baseState: null,         queue: null,        baseUpdate: null,        next: null,      }    */
  5.   const hook = mountWorkInProgressHook();
  6. // 如果传入的是函数 直接执行,所以第一次这个参数是 undefined
  7.   if (typeof initialState === 'function') {
  8.     initialState = initialState();
  9.   }
  10.   hook.memoizedState = hook.baseState = initialState;
  11.   const queue = (hook.queue = {
  12.     last: null,
  13.     dispatch: null,
  14.     lastRenderedReducer: basicStateReducer,
  15.     lastRenderedState: (initialState: any),
  16.   });
  17.     /*    定义 dispatch 相当于    const dispatch = queue.dispatch =    dispatchAction.bind(null,currentlyRenderingFiber,queue);    */
  18.   const dispatch: Dispatch<
  19.     BasicStateAction<S>,
  20.   > = (queue.dispatch = (dispatchAction.bind(
  21.     null,
  22.     // Flow doesn't know this is non-null, but we do.
  23.     ((currentlyRenderingFiber: any): Fiber),
  24.     queue,
  25.   ): any));
  26. // 可以看到这个dispatch就是dispatchAction绑定了对应的 currentlyRenderingFiber 和 queue。最后return:
  27.   return [hook.memoizedState, dispatch];
  28. }
复制代码
dispatchAction 源码
  1. function dispatchAction<A>(fiber: Fiber, queue: UpdateQueue<A>, action: A) {
  2.   //... 省略验证的代码
  3.   const alternate = fiber.alternate;
  4.     /*    这其实就是判断这个更新是否是在渲染过程中产生的,currentlyRenderingFiber只有在FunctionalComponent更新的过程中才会被设置,在离开更新的时候设置为null,所以只要存在并更产生更新的Fiber相等,说明这个更新是在当前渲染中产生的,则这是一次reRender。所有更新过程中产生的更新记录在renderPhaseUpdates这个Map上,以每个Hook的queue为key。对于不是更新过程中产生的更新,则直接在queue上执行操作就行了,注意在最后会发起一次scheduleWork的调度。    */
  5.   if (
  6.     fiber === currentlyRenderingFiber ||
  7.     (alternate !== null && alternate === currentlyRenderingFiber)
  8.   ) {
  9.     didScheduleRenderPhaseUpdate = true;
  10.     const update: Update<A> = {
  11.       expirationTime: renderExpirationTime,
  12.       action,
  13.       next: null,
  14.     };
  15.     if (renderPhaseUpdates === null) {
  16.       renderPhaseUpdates = new Map();
  17.     }
  18.     const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
  19.     if (firstRenderPhaseUpdate === undefined) {
  20.       renderPhaseUpdates.set(queue, update);
  21.     } else {
  22.       // Append the update to the end of the list.
  23.       let lastRenderPhaseUpdate = firstRenderPhaseUpdate;
  24.       while (lastRenderPhaseUpdate.next !== null) {
  25.         lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
  26.       }
  27.       lastRenderPhaseUpdate.next = update;
  28.     }
  29.   } else {
  30.     const currentTime = requestCurrentTime();
  31.     const expirationTime = computeExpirationForFiber(currentTime, fiber);
  32.     const update: Update<A> = {
  33.       expirationTime,
  34.       action,
  35.       next: null,
  36.     };
  37.     flushPassiveEffects();
  38.     // Append the update to the end of the list.
  39.     const last = queue.last;
  40.     if (last === null) {
  41.       // This is the first update. Create a circular list.
  42.       update.next = update;
  43.     } else {
  44.       const first = last.next;
  45.       if (first !== null) {
  46.         // Still circular.
  47.         update.next = first;
  48.       }
  49.       last.next = update;
  50.     }
  51.     queue.last = update;
  52.     scheduleWork(fiber, expirationTime);
  53.   }
  54. }
复制代码
mountReducer 源码
多勒第三个参数,是函数执行,默认初始状态 undefined
其他的和 上面的 mountState 大同小异
  1. function mountReducer<S, I, A>(
  2.   reducer: (S, A) => S,
  3.   initialArg: I,
  4.   init?: I => S,
  5. ): [S, Dispatch<A>] {
  6.   const hook = mountWorkInProgressHook();
  7.   let initialState;
  8.   if (init !== undefined) {
  9.     initialState = init(initialArg);
  10.   } else {
  11.     initialState = ((initialArg: any): S);
  12.   }
  13.     // 其他和 useState 一样
  14.   hook.memoizedState = hook.baseState = initialState;
  15.   const queue = (hook.queue = {
  16.     last: null,
  17.     dispatch: null,
  18.     lastRenderedReducer: reducer,
  19.     lastRenderedState: (initialState: any),
  20.   });
  21.   const dispatch: Dispatch<A> = (queue.dispatch = (dispatchAction.bind(
  22.     null,
  23.     // Flow doesn't know this is non-null, but we do.
  24.     ((currentlyRenderingFiber: any): Fiber),
  25.     queue,
  26.   ): any));
  27.   return [hook.memoizedState, dispatch];
  28. }
复制代码
通过 react 源码中,可以看出 useState 是特殊的 useReducer
    可见useState不过就是个语法糖,本质其实就是useReducerupdateState 复用了 updateReducer(区别只是 updateState 将 reducer 设置为 updateReducer)mountState 虽没直接调用 mountReducer,但是几乎大同小异(区别只是 mountState 将 reducer 设置为basicStateReducer)
注:这里仅是 react 源码,至于重新渲染这块 react-dom 还没有去深入了解。
更新:
分两种情况,是否是 reRender,所谓reRender就是说在当前更新周期中又产生了新的更新,就继续执行这些更新知道当前渲染周期中没有更新为止
他们基本的操作是一致的,就是根据 reducer 和 update.action 来创建新的 state,并赋值给Hook.memoizedState 以及 Hook.baseState。
注意这里,对于非reRender得情况,我们会对每个更新判断其优先级,如果不是当前整体更新优先级内得更新会跳过,第一个跳过得Update会变成新的baseUpdate,他记录了在之后所有得Update,即便是优先级比他高得,因为在他被执行得时候,需要保证后续的更新要在他更新之后的基础上再次执行,因为结果可能会不一样。
来源
preact 中的 hooks
Preact 最优质的开源 React 替代品!(轻量级 3kb)
注意:这里的替代是指如果不用 react 的话,可以使用这个。而不是取代。
useState 源码解析
调用了 useReducer 源码
  1. export function useState(initialState) {
  2.     return useReducer(invokeOrReturn, initialState);
  3. }
复制代码
useReducer 源码解析
  1. // 模块全局定义
  2. /** @type {number} */
  3. let currentIndex; // 状态的索引,也就是前面模拟实现 useState 时候所说的指针
  4. let currentComponent; // 当前的组件
  5. export function useReducer(reducer, initialState, init) {
  6.     /** @type {import('./internal').ReducerHookState} */
  7.     // 通过 getHookState 方法来获取 hooks
  8.     const hookState = getHookState(currentIndex++);
  9.     // 如果没有组件 也就是初始渲染
  10.     if (!hookState._component) {
  11.         hookState._component = currentComponent;
  12.         hookState._value = [
  13.             // 没有 init 执行 invokeOrReturn
  14.                 // invokeOrReturn 方法判断 initialState 是否是函数
  15.                 // 是函数 initialState(null) 因为初始化没有值默认为null
  16.                 // 不是函数 直接返回 initialState
  17.             !init ? invokeOrReturn(null, initialState) : init(initialState),
  18.             action => {
  19.                 // reducer == invokeOrReturn
  20.                 const nextValue = reducer(hookState._value[0], action);
  21.                 // 如果当前的值,不等于 下一个值
  22.                 // 也就是更新的状态的值,不等于之前的状态的值
  23.                 if (hookState._value[0]!==nextValue) {
  24.                     // 储存最新的状态
  25.                     hookState._value[0] = nextValue;
  26.                     // 渲染组件
  27.                     hookState._component.setState({});
  28.                 }
  29.             }
  30.         ];
  31.     }
  32.     // hookState._value 数据格式也就是 [satea:any, action:Function] 的数据格式拉
  33.     return hookState._value;
  34. }
复制代码
getHookState 方法
  1. function getHookState(index) {
  2.     if (options._hook) options._hook(currentComponent);
  3.     const hooks = currentComponent.__hooks || (currentComponent.__hooks = { _list: [], _pendingEffects: [], _pendingLayoutEffects: [] });
  4.     if (index >= hooks._list.length) {
  5.         hooks._list.push({});
  6.     }
  7.     return hooks._list[index];
  8. }
复制代码
invokeOrReturn 方法
  1. function invokeOrReturn(arg, f) {
  2.     return typeof f === 'function' ? f(arg) : f;
  3. }
复制代码
总结

使用 hooks 几个月了。基本上所有类组件我都使用函数式组件来写。现在 react 社区的很多组件,都也开始支持hooks。大概了解了点重要的源码,做到知其然也知其所以然,那么在实际工作中使用他可以减少不必要的 bug,提高效率。
到此这篇关于React深入浅出分析Hooks源码的文章就介绍到这了,更多相关React Hooks内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行