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

后端 未结 8 1748
梦谈多话
梦谈多话 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-25 10:18

    You can access the latest state in setState callback. But the intention is not clear, we never want to setState in this case, it may confuse other people when they read your code. So you may want to wrap it in another hook that can express what you want better

    function useExtendedState(initialState: T) {
      const [state, setState] = React.useState(initialState);
      const getLatestState = () => {
        return new Promise((resolve, reject) => {
          setState((s) => {
            resolve(s);
            return s;
          });
        });
      };
    
      return [state, setState, getLatestState] as const;
    }
    

    Usage

    const [counter, setCounter, getCounter] = useExtendedState(0);
    
    ...
    
    getCounter().then((counter) => /* ... */)
    
    // you can also use await in async callback
    const counter = await getCounter();
    

    Live Demo

提交回复
热议问题