【发布时间】:2023-01-14 09:02:14
【问题描述】:
考虑以下代码:
function Middle() {
const [show, setShow]=useState(false);
return (
<div>
<button onClick={()=>setShow(v=>!v)}>MIDDLE</button>
<Bottom visible={show}/>
</div>
);
}
function Bottom(props) {
const {visible} = props;
const state = useRef(0);
useEffect(() => {
console.log('Hey', state.current++);
});
return (
<>
{visible && <div>BOTTOM</div> }
</>
);
}
每当我们点击按钮 MIDDLE 时,依次挂载/卸载;至少这是我的理解,因为它被添加到 DOM 中/从 DOM 中删除。因此,我应该期望的是不要坚持它的状态。相反,它确实发生的是 state.current 总是增加它的价值。我真的很困惑...
【问题讨论】:
-
将您拥有的内容与中间组件中的
{ show && <Bottom visible={show} /> }进行比较。
标签: reactjs