【问题标题】:React.js: useState Hook Setter is not updating the stateReact.js:useState Hook Setter 没有更新状态
【发布时间】: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);
    }
};

【问题讨论】:

标签: reactjs react-hooks use-state


【解决方案1】:

我猜_HandleShown在addEventListener...中使用,在这种情况下你想使用isHidden来比较你需要这样做,因为JS中的闭包。

const ImageRef = useRef(null);

// Initial Value Passed
const [isHidden, setShown] = useState(true);

const _HandleShown = () => {
    const nextState = window.scrollY > ImageRef.current.offsetHeight;

    setShown(prevIsHidden =>{
      if (prevIsHidden !== nextState) {
        return nextState
      }
      return prevIsHidden
    });
};

【讨论】:

    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多