React hooks: accessing up-to-date state from within a callback

后端 未结 8 1754
梦谈多话
梦谈多话 2020-12-25 09:35

EDIT (22 June 2020): as this question has some renewed interest, I realise there may be a few points of confusion. So I would like to highlight: the example in the question

8条回答
  •  不思量自难忘°
    2020-12-25 10:28

    The only method i know is to call the setState(current_value => ...) function and use the current_value in ur logic. Just make sure you return it back. Ex:

    const myPollingFunction = () => {
        setInterval(() => {
            setState(latest_value => {
                // do something with latest_value
                return latest_value;    
            }
        }, 1000);
    };
    

提交回复
热议问题