gpt4 book ai didi

javascript - React Hooks 的逻辑在哪里?

转载 作者:行者123 更新时间:2023-12-02 16:01:24 28 4
gpt4 key购买 nike

最近我开始阅读 React Hooks 代码,我看到了这个。

function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create, deps);
}
function useLayoutEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
{
var dispatcher = resolveDispatcher();
return dispatcher.useDebugValue(value, formatterFn);
}
}

调度器是一个由resolveDispatcher()初始化的对象。

function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;

if (!(dispatcher !== null)) {
{
throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component..." );
}
}

return dispatcher;
}

ReactCurrentDispatcher 是一个对象,它有一个名为 current 的属性。

var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};

现在我的问题是 React 如何以及在何处处理钩子(Hook)的逻辑?useImperativeHandle or ...的逻辑在哪里?

最佳答案

一般来说,为了回答这样的问题,我会克隆 repo 并使用 aggit grep:

(react) $ git grep useImperativeHandle
[...]
packages/react-reconciler/src/ReactFiberHooks.new.js: useImperativeHandle<T>(
[...]

这让我找到了 these mappings就在这里——例如,useImperativeHandle 的代码似乎是 these three functions .

了解它们如何工作以及如何与 React 纤程系统交互是另一个难题。

关于javascript - React Hooks 的逻辑在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70562215/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com