简体   繁体   中英

React.js: useState Hook Setter is not updating the state

I am trying to update the state conditionally to trigger visibility.

However when I pass a initial value to the useState hook, it updates only once.

Code 1 : Updating only once when there is an initial value

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);
    }
};

Code 2 : Working as expected when there is no initial value

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);
    }
};

I guess _HandleShown is use in addEventListener... , in that case you want to use isHidden to compare you need to do this, because of closure in 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 }); };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM