克隆useState钩子

时间:2020-04-11 16:57:39

标签: javascript reactjs react-hooks

阅读本文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时我需要更改什么?

0 个答案:

没有答案