英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论