【发布时间】:2022-11-28 19:30:14
【问题描述】:
另一个 React 18 严格模式问题。我知道 React 会调用渲染和效果函数两次,以突出显示即将推出的功能的潜在内存泄漏。我还不明白的是如何正确处理它。我的问题是我无法正确卸载第一个渲染结果,因为两个 useEffect 调用是在第二个渲染的状态下执行的。这是一个展示我的意思的例子。
const ref = useRef(9);
const id = useId();
console.log('@@ initial id', id);
console.log('@@ initial ref', ref.current);
ref.current = Math.random();
console.log('@@ random ref', ref.current);
useEffect(() => {
console.log('@@ effect id', id);
console.log('@@ effect ref', ref.current);
return () => {
console.log('@@ unmount id', id);
console.log('@@ unmount ref', ref.current);
};
});
这是日志输出
@@ initial id :r0:
@@ initial ref 9
@@ random ref 0.26890444169781214
@@ initial id :r1:
@@ initial ref 9
@@ random ref 0.7330565878991766
@@ effect id :r1: <<--- first effect doesn't use data of first render cycle
@@ effect ref 0.7330565878991766
@@ unmount id :r1:
@@ unmount ref 0.7330565878991766
@@ effect id :r1:
@@ effect ref 0.7330565878991766
如您所见,在第一个渲染周期的状态下没有 useEffect 调用,第二个渲染周期也没有为您提供第一个渲染周期的引用(它再次用 9 初始化,而不是 0.26890444169781214。还有useId 钩子返回两个不同的 ID,其中第二个 ID 也保留在进一步的渲染周期中。 这是错误还是预期的行为?如果是预期的,有没有办法解决这个问题?
【问题讨论】:
-
它似乎在效果之前做了两个渲染周期,然后在不运行渲染周期的情况下进行效果清理,看起来 dev stritct 模式被破坏了 :P,它在生产中只运行一次,但对 dev stritct 模式的解释没有匹配这个输出
标签: javascript reactjs