简体   繁体   中英

How to get the latest state value? reactjs

I have simple custom hooks created below. My problem is, the state seems does not updating.

The console always logs 1 , when I call goToNextIndex

const useTag = () => {
    const [tagIndex, setTagIndex] = useState(0);

    const goToNextIndex = () => {
        const updatedIndex = tagIndex + 1;
        console.log(updatedIndex);
        setTagIndex(updatedIndex);
    };
    
    return {
        tagIndex,
        goToNextIndex,
    };
}

One way to solve this would be for the consumer of useTag to properly respond to changes of the goToNextIndex function, so it doesn't have a stale closure - for example, by always using the prop value, instead of using only the value on mount, which would become out of date:

 const useTag = () => { const [tagIndex, setTagIndex] = React.useState(0); const goToNextIndex = () => { const updatedIndex = tagIndex + 1; console.log(updatedIndex); setTagIndex(updatedIndex); }; return { tagIndex, goToNextIndex, }; } const App = () => { const { tagIndex, goToNextIndex } = useTag(); return <button onClick={goToNextIndex}>{tagIndex}</button>; }; ReactDOM.render(<App />, document.querySelector('.react'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>

This method would be preferable when possible, since the code is as clean as it can be - often it's possible, but occasionally it wouldn't be, if asynchronous code is involved.

Another way would be to log inside the setTagIndex callback:

 const useTag = () => { const [tagIndex, setTagIndex] = React.useState(0); const goToNextIndex = () => { setTagIndex((mostCurrentIndex) => { const updatedIndex = mostCurrentIndex + 1; console.log(updatedIndex); return updatedIndex; }); }; return { tagIndex, goToNextIndex, }; } const App = () => { const { tagIndex, goToNextIndex } = useTag(); return <button onClick={goToNextIndex}>{tagIndex}</button>; }; ReactDOM.render(<App />, document.querySelector('.react'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>

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