这个简单的React组件中额外渲染的原因是什么?

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

What's the reason for the extra renders in this simple React component?

问题

这段代码的控制台输出如下:

RENDER
RETURN
RENDER
RETURN
EFFECT
EFFECT
  • 为什么组件在触发 useEffect 之前完全渲染两次?
  • 为什么 useEffect 运行两次?

我预期的输出是:

RENDER
RETURN
EFFECT

(即组件渲染,然后触发 useEffect)

英文:

If I have this code:

export const App = () => {
  return <Child />;
};

const Child = () => {
  console.log("RENDER");

  useEffect(() => {
    console.log("EFFECT");
  }, []);

  console.log("RETURN");

  return <div>Hello world</div>;
};

The output in the console is:

RENDER
RETURN
RENDER
RETURN
EFFECT
EFFECT
  • Why does the component render fully twice before the useEffect is triggered?
  • Why does the effect run twice?

I expected the output to be:

RENDER
RETURN
EFFECT

(i.e. the component renders and then the useEffect is triggered)

答案1

得分: 2

I think your main.tsx(或main.jsx)has <React.StrictMode><App /><React.StrictMode>
Strict Mode

英文:

I think your main.tsx(or main.jsx) have <React.StrictMode><App /><React.StrictMode>
Strict Mode

huangapple
  • 本文由 发表于 2023年6月15日 15:49:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480226.html
匿名

发表评论

匿名网友

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

确定