<button onClick={() => setValue(value + 1)}>+
{value}
)
}
复制代码
结果是这样:
有没有办法破解限制呢?
如果要破解全局索引递增导致的 bug,那么我们可以考虑换种方式存储 Hook 状态。
如果不用下标存储,是否可以考虑用一个全局唯一的 key 来保存 Hook,这样不是就可以绕过下标导致的混乱了吗?
比如 useState
这个 API 改造成这样:
export default function App() {
if (Math.random() > 0.5) {
useState(10000, ‘key1’);
}
const [value, setValue] = useState(0, “key2”);
return (
<button onClick={() => setValue(value + 1)}>+
{value}
);
}
复制代码
这样,通过 _hooks['key']
来查找,就无所谓前序的 Hook 出现的任何意外情况了。
也就是说,原本的存储方式是:
_hooks: [
{ value: ‘first’, update: function },
{ value: ‘second’, update: function },
]
复制代码
改造后:
_hooks: [
key1: { value: ‘first’, update: function },
key2: { value: ‘second’, update: function },
]
复制代码
注意,数组本身就支持对象的 key 值特性,不需要改造 _hooks
的结构。
来试着改造一下 Preact 源码,它的 Hook 包的位置在 hooks/src/index.js 下,找到 useState
方法:
export function useState(initialState) {
currentHook = 1;
return useReducer(invokeOrReturn, initialState, undefined);
}
复制代码
它的底层调用了 useReducer
,所以新增加一个 key
参数透传下去:
- export function useState(initialState, key) {
currentHook = 1;
- return useReducer(invokeOrReturn, initialState, undefined, key);
}
复制代码
useReducer
原本是通过全局索引去获取 Hook state:
// 全局索引
let currentIndex
export function useReducer(reducer, initialState, init) {
const hookState = getHookState(currentIndex++, 2);
hookState._reducer = reducer;
return hookState._value;
}
复制代码
改造成兼容版本,有 key 的时候优先传入 key 值:
// 全局索引
let currentIndex
-
export function useReducer(reducer, initialState, init, key) {
-
const hookState = getHookState(key || currentIndex++, 2);
hookState._reducer = reducer;
return hookState._value;
}
复制代码
最后改造一下 getHookState
方法:
function getHookState(index, type) {
const hooks =
currentComponent.__hooks ||
(currentComponent.__hooks = {
_list: [],
_pendingEffects: [],
});
// 传入 key 值是 string 或 symbol 都可以
-
if (typeof index !== ‘number’) {
-
if (!hooks._list[index]) {
-
hooks._list[index] = {};
-
}
-
} else {
if (index >= hooks._list.length) {
hooks._list.push({});
}
}
// 这里天然支持 key 值取用的方式
return hooks._list[index];
}
复制代码
这里设计成传入 key
值的时候,初始化就不往数组里 push
新状态,而是直接通过下标写入即可,原本的取状态的写法 hooks._list[index]
本身就支持通过 key
从数组上取值,不用改动。
至此,改造就完成了。
来试试新用法:
export default function App() {
if (Math.random() > 0.5) {
useState(10000, ‘key1’);
}
const [value, setValue] = useState(0, ‘key2’);
return (
<button onClick={() => setValue(value + 1)}>+
{value}
);
}
复制代码
事实上 React 团队也考虑过给每次调用加一个 key
值的设计,在 Dan Abramov 的 为什么顺序调用对 React Hooks 很重要? 中已经详细解释过这个提案。
多重的缺陷导致这个提案被否决了,尤其是在遇到自定义 Hook 的时候,比如你提取了一个 useFormInput
:
const valueKey = Symbol();
function useFormInput() {
const [value, setValue] = useState(valueKey);
return {
value,
onChange(e) {
setValue(e.target.value);
},
};
}
复制代码
然后在组件中多次调用它:
function Form() {
// 使用 Symbol
const name = useFormInput();
// 又一次使用了同一个 Symbol
const surname = useFormInput();
// …
return (
<>
<input {…name} />
<input {…surname} />
{/* … */}
</>
)
}
复制代码
此时这个通过 key
寻找 Hook state 的方式就会发生冲突。
但我的想法是,能不能借助 babel 插件的编译能力,实现编译期自动为每一次 Hook 调用都注入一个 key
, 伪代码如下:
traverse(node) {
if (isReactHookInvoking(node)) {
addFunctionParameter(node, getUniqKey(node))
}
}
复制代码
生成这样的代码:
function Form() {