【发布时间】:2020-09-24 22:44:29
【问题描述】:
我正在尝试有条件地更新状态以触发可见性。
但是,当我将初始值传递给 useState 挂钩时,它只会更新一次。
代码1:有初始值时只更新一次
const ImageRef = useRef(null);
// Initial Value Passed
const [isHidden, setShown] = useState(true);
const _HandleShown = () => {
const nextState = window.scrollY > ImageRef.current.offsetHeight;
if (isHidden !== nextState) {
setShown(nextState);
}
};
代码2:在没有初始值时按预期工作
const ImageRef = useRef(null);
// No Initial Value Passed
const [isHidden, setShown] = useState();
const _HandleShown = () => {
const nextState = window.scrollY > ImageRef.current.offsetHeight;
if (isHidden !== nextState) {
setShown(nextState);
}
};
【问题讨论】:
-
好像是这个问题,只更新一次,请检查一次stackoverflow.com/q/57296445/2129071
标签: reactjs react-hooks use-state