You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// useStateexportfunctionuseState<S>(initialState: (()=>S)|S){constdispatcher=resolveDispatcher();returndispatcher.useState(initialState);}
... // more codeexportfunctionuseEffect(create: ()=>(()=>void)|void,inputs: Array<mixed>|void|null,){constdispatcher=resolveDispatcher();returndispatcher.useEffect(create,inputs);}
... // more code
从以上代码可以得到几点信息:
代码中针对 useContext 部分,使用了 warning 抛出警告
都调用了 resolveDispatcher() 函数;
resolveDispatcher() 会返回一个 dispatcher;
dispatcher 中实现了所有的 hook;
使用了 Flow(同其他源码)。
接下来,查看 resolveDispatcher() 函数:
functionresolveDispatcher(){constdispatcher=ReactCurrentDispatcher.current;invariant(dispatcher!==null,'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for'+' one of the following reasons:\n'+'1. You might have mismatching versions of React and the renderer (such as React DOM)\n'+'2. You might be breaking the Rules of Hooks\n'+'3. You might have more than one copy of React in the same app\n'+'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',);returndispatcher;}
我们会从以下几个文件来阅读 Hook 相关源码:
React.js
话不多说,让我们一探究竟!
首先,代码阅读先从入口开始:
React 引入方式如下:
如果使用了 Component,Hook 之类代码,引入方式如下所示:
由上述代码可以知,Hook 绑定在 React 对象之中。
按照这条线索寻找,会在
react/src/React.js
文件中发现如下代码:由此可知,Hook 相关的逻辑都保存在了
react/src/ReactHooks.js
当中。ReactHooks.js
打开
react/src/ReactHooks.js
文件,先来看看引入的头文件:从头文件中我们得出以下信息:
useContext
作类型判断;invariant
作断言,说明某些代码执行不过,可能会中端;warning
抛出警告信息;ReactCurrentDispatcher
暂时不知其作用。看完头文件,来看看 Hook 的相关实现:
从以上代码可以得到几点信息:
useContext
部分,使用了warning
抛出警告resolveDispatcher()
函数;resolveDispatcher()
会返回一个dispatcher
;dispatcher
中实现了所有的 hook;Flow
(同其他源码)。接下来,查看
resolveDispatcher()
函数:通过以上代码可知:
dispatcher
实质上就是通过ReactCurrentDispatcher.current
获取的;dispatcher
后,使用invariant
对dispatcher
进行了类似于断言的操作(用于进行规则和版本鉴别);综上所述,我猜测 Hook 的核心文件可能是
ReactCurrentDispatcher.js
。ReactCurrentDispatcher.js
然而,我错了。
此文件的代码如下:
The text was updated successfully, but these errors were encountered: