【发布时间】:2023-01-24 17:02:36
【问题描述】:
在以下 App.js 的最小工作示例中:
import { useState, useEffect } from "react";
export default function App() {
const [isShown, setIsShown] = useState(true);
return (
<>
<button onClick = {() => setIsShown(!isShown)}>
{isShown? 'Hide Counter' : 'Show Counter'}
</button>
{isShown? <Counter /> : null}
</>
);
}
function Counter(){
const [count, setCount] = useState(0);
const [bool, setBool] = useState(false);
useEffect(() => {
console.log('render');
});
useEffect(() => {
console.log('mounted');
}, []);
return (
<div className="counter">
<button onClick={() =>setBool(!bool)}>Re-Render</button>
<button onClick={() =>setCount(count + 1)}>Increment</button>
<p> Count: {count}</p>
</div>
);
}
每当我刷新页面或单击“隐藏计数器”然后单击“显示计数器”时,我都会得到两组 console.logs(即消息“呈现”和“已安装”显示两次)。我的期望是“render”和“show”应该只出现一次。在当前情况下,这似乎意味着每次加载页面时组件都会呈现两次。我已经在 Firefox 和 Chrome 上对此进行了测试,并在两者中发现了相同的行为。
为什么会这样,我该如何开始调试呢?
【问题讨论】:
-
这回答了你的问题了吗? Why is my React component is rendering twice?
标签: reactjs