如何在自定义钩子函数中访问新的useReducer状态

时间:2020-02-25 08:29:19

标签: reactjs react-hooks use-reducer

我有一个使用useReducer的自定义钩子。

function useMyCustomHook() {
   const [state, dispatch] = useReducer(EntityReducer, initialState);

   // console.log(state); // 1- state is up to date here

   const customDispatch = (action) => {
       dispatch({ ...action }); // first call EntityReducer by action.type

       //2- I use state and dispatch here(for example:use state for call an api, then dispatch response)
       // but the state is previous not new state?

       switch (action.type) {
           case "something":
               // use dispatch and state here                     
               return state;
       }
   }

   return [state, customDispatch];
}

使用自定义钩子:

function HomePage(props) {
    const [state, dispatch] = useMyCustomHook();

    // for example use dispatch on click a button

    return (<div>...</div>)
}

问题:statecustomDispatch内部的上一个状态。我该如何解决?

谢谢。

1 个答案:

答案 0 :(得分:4)

据我所知,您的状态陷入了反应钩(由闭包捕获)中。

那么您有以下解决方案:

1-useEffect具有依赖项

useEffect(() => {
 // state will be updated here
 // declare 'customDispatch' here
}, [state,...]);
useRef内部的

2-{{​​1}}如:

useMyCustomHook