阅读本文https://www.netlify.com/blog/2019/03/11/deep-dive-how-do-react-hooks-really-work/时,我正在尝试为useState
创建等效的源代码。
所以,这就是代码:
const MyReact = (function() {
let _val;
return {
useState(initialValue) {
_val = _val || initialValue;
function setState(newVal) {
_val = newVal
}
return [_val, setState];
}
}
})()
function Counter() {
const [count, setCount] = MyReact.useState(0);
setCount(2);
setTimeout(()=>console.log(count), 2000);
}
Counter(); // 0
上面的代码与useState
逻辑不匹配,因为它应该输出2。以简化的方式克隆useState
时我需要更改什么?