【发布时间】:2021-11-30 07:45:15
【问题描述】:
我正在尝试了解如何使用纯 Javascript 实现 useState 挂钩。我卡在了使用闭包的部分。
这是代码。
const React = (function () {
let hooks = [];
let idx = 0;
function useState(initVal) {
const _idx = idx;
console.log(_idx) // 0, 1
const state = hooks[idx] || initVal;
const setState = newVal => {
hooks[_idx] = newVal;
};
idx++;
return [state, setState];
}
function render(Component) {
idx = 0;
const C = Component();
C.render();
return C;
}
return { useState, render };
})();
function Component() {
const [count, setCount] = React.useState(1);
const [text, setText] = React.useState('apple');
return {
render: () => console.log({ count, text }),
click: () => setCount(count + 1),
type: (word) => setText(word),
}
}
var App = React.render(Component); // {count: 1, text: "apple"}
App.click();
var App = React.render(Component); // {count: 2, text: "apple"}
App.type('pear');
var App = React.render(Component); // {count: 2, text: "pear"}
当 setState 函数(点击或输入)被调用时,它会根据 hooks 数组的索引更新值,计数为 0,文本为 1。
这意味着useState中的setState函数通过javascript闭包记住了每个状态(计数和文本)的_idx的值?
【问题讨论】:
-
问题不清楚。 javascript 闭包是什么意思?
标签: javascript reactjs closures