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

Mor*_*emi 2 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];
}
Run Code Online (Sandbox Code Playgroud)

使用自定义钩子:

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

    // for example use dispatch on click a button

    return (<div>...</div>)
}
Run Code Online (Sandbox Code Playgroud)

问题:state里面是 prev 状态customDispatch。我怎样才能解决这个问题?

提前致谢。

小智 5

据我所知,你的状态在react-hooks中陈旧(通过闭包捕获)。

然后你有这些解决方案:

1-useEffect具有依赖关系

useEffect(() => {
 // state will be updated here
 // declare 'customDispatch' here
}, [state,...]);
Run Code Online (Sandbox Code Playgroud)

2-useRef里面useMyCustomHook像:

const [state, dispatch] = useReducer(EntityReducer, initialState);
const stateRef=useRef(state);

useEffect(() => {
        stateRef.current=state;
});

const customDispatch = (action) => {
// use state.current instead of state(state.current will be updated)
}
Run Code Online (Sandbox Code Playgroud)