useEffect在组件重新渲染之前为什么会运行?

huangapple go评论59阅读模式
英文:

Why is useEffect running before component re-render?

问题

我是React的新手,这是一个非常简单的计数器,每次增加5个值,我了解到useEffect在每次组件重新渲染/依赖变量更改后执行。但我发现useEffect(即alert)在h1中的值更改之前出现。

import { useEffect, useState } from "react";

export default function App() {
const [number, setNumber] = useState(0);

let prev = 0;

useEffect(() => {
if (number !== 0) {
alert("Number changed to " + number);
}
}, [prev, number]);

console.log(prev);

return (
<>

{number}

<button
onClick={() => {
setNumber((n) => {
prev = n;
return n + 5;
});
}}>
+5

</>
);
}


期望结果:在h1的值增加5之后发生警报。

当前结果:警报首先出现,然后在关闭警报后增加h1的值。
英文:

I am new to react and this is a very simple counter that increments value by 5, I learnt that useEffect is executed after every component re-render/dependency variable change. But I found that useEffect (i.e alert) is appearing before the value in the h1 changes

import { useEffect, useState } from &quot;react&quot;;

export default function App() {
const [number, setNumber] = useState(0);

  let prev = 0;

  useEffect(() =&gt; {
    if (number !== 0) {
      alert(&quot;Number changed to &quot; + number);
    }
  }, [prev, number]);

  console.log(prev);

  return (
    &lt;&gt;
      &lt;h1&gt;{number}&lt;/h1&gt;
      &lt;button
        onClick={() =&gt; {
          setNumber((n) =&gt; {
            prev = n;
            return n + 5;
          });
        }}&gt;
        +5
      &lt;/button&gt;
    &lt;/&gt;
  );
}

Expected Outcome: alert happens after h1 value increments by 5

Current Result: alert comes first and h1 value increments after closing the alert

答案1

得分: 1

这是 useEffect 运行的时机:

    useEffect(() => {
      /* 在每次渲染时都运行(首次渲染和每次组件重新渲染时) */
    })

    useEffect(() => {
      /* 仅在首次渲染时运行! */
    }, [])

    useEffect(() => {
      /* 在首次渲染时以及 someDependency 更新时运行! */
    }, [someDependency])

因此,在您的情况下,它会在首次渲染时运行,当数字发生变化时运行,以及当 prev 发生变化时运行。另外,请不要像您目前这样更改 prev,否则会导致无限循环!

英文:

This is when useEffect runs:

useEffect(() =&gt; {
  /* Runs at every (First time, and anytime the component is rendered) render! */
})

useEffect(() =&gt; {
  /* Runs only when the component is rendered for the first time! */
}, [])

useEffect(() =&gt; {
  /* Runs when the component is rendered for the first time and whenever the someDependency is updated! */
}, [someDependency])

Therefore, in your case, it runs when the component is rendered for the first time, when the number changes, and when the prev changes. Also, do not change prev the way you are doing it right now, it will cause an infinite loop!

答案2

得分: 0

useEffect的运行方式基本上类似于componentDidMount,因此它在组件挂载后首次运行,然后在每次重新渲染后运行。

英文:

useEffect runs basically like componentDidMount,

so it runs first time after the component mounted and then after every re-render

huangapple
  • 本文由 发表于 2023年2月14日 22:31:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75449303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定