我有一个使用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>)
}
问题:state
是customDispatch
内部的上一个状态。我该如何解决?
谢谢。
答案 0 :(得分:4)
据我所知,您的状态陷入了反应钩(由闭包捕获)中。
那么您有以下解决方案:
1-useEffect
具有依赖项
useEffect(() => {
// state will be updated here
// declare 'customDispatch' here
}, [state,...]);
在useRef
内部的2-{{1}}如:
useMyCustomHook