reactjs - 使用 `new` 关键字作为参数的 useState

我正在构建一个单独的服务来处理复杂的事情,该服务是一个类,只是为了测试建议,我在 useState 中模拟。

关键是我忘记了构造函数中的 console.log 并意识到类构造函数在组件重新呈现时被调用了很多次。这种行为不会导致意想不到的行为或类似的事情,但我问自己为什么会这样,因为我知道在 useState 中声明的东西在它的调用中不会重复自己,但是显然我错了导致以下问题的原因。

  1. 为什么会这样? (我没有找到关于这个具体案例的任何文档)
  2. 这会影响内存力或处理能力吗? (因为这个类被重新实例化了很多次)
  3. 垃圾收集器收集那个?

我创建了一个小沙盒来举例说明我在说什么,您可以看到控制台上多次显示“Called”字样,并一直显示单击按钮。 https://codesandbox.io/s/new-class-inside-usestate-w9et3?file=/src/App.js

最佳答案

这是一个常见的错误,在 React 文档中并未明确提及。

每次呈现 时,函数组件的主体被执行。 从构造函数中记录日志是预期的行为,因为编写这样的代码:

const [example] = useState(new Foo());

结果会在每次渲染时调用 new Foo()是的,尽管 useState 没有考虑到它的结果钩子(Hook)。


因此你想制作lazy initial正如你希望它被调用一次:

const [example] = useState(() => new Foo());

The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded. If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render.

关于reactjs - 使用 `new` 关键字作为参数的 useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64131341/

相关文章:

swift - 在 RealityKit 中启用手势

javascript - 使用 useEffect 加载脚本

c# - 无法将 TextMeshPro 文本获取到 Unity 中的变量槽

Haskell - 如何将矩阵(二维数组)分成几组

python - 重复值 n 次,n 在一个数组中

python - 为什么 python 的 "gc.collect()"没有按预期工作?

java - 检查一个数组列表是否包含两个字符串

python-3.x - Pygame - 不存在 "Setup"文件,正在运行 "buildcon

python - 如何使用 numba 在 GPU 上推广快速矩阵乘法

r - 按列计算唯一值