【问题标题】:Is this how closure works in useState hook?这是闭包在 useState 钩子中的工作方式吗?
【发布时间】: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


【解决方案1】:

这意味着useState中的setState函数通过javascript闭包记住了每个状态(计数和文本)的_idx的值?

是的。当调用useState 时,它使用idx 获取下一个可用索引并将其存储在常量_idx 中。返回的setState 函数形成一个闭包,因此即使useState 已完成执行,它也会记住与其状态相对应的_idx

我卡在了使用闭包的部分。

其他使用闭包的地方:

  • React 模块内的useStaterender 函数形成了hooksidx 的闭包。因此,即使在 React(一个 iife)完成执行之后,这些函数也能够读取/写入这些变量。
  • renderclicktype 函数形成一个闭包。 render 方法关闭 Component。因此,即使在 Component 函数完成执行之后,它也能够访问 counttext。 同样,clicktype 形成一个闭包,因此可以调用在 Component 范围内定义的 setCountsetText 函数。

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 2020-11-03
    • 2023-01-09
    • 1970-01-01
    • 2022-07-14
    • 2021-11-11
    • 1970-01-01
    • 2021-04-10
    • 2020-09-06
    相关资源
    最近更新 更多