如何在自定义挂钩函数中访问新的 useReducer 状态
How to access to new state of useReducer inside custom hook's function
我有一个使用 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
中的上一个状态。我该如何解决这个问题?
提前致谢。
据我所知,你的状态在 react-hooks 中过时了(被闭包捕获)。
那么你有这些解决方案:
1-useEffect
具有依赖项
useEffect(() => {
// state will be updated here
// declare 'customDispatch' here
}, [state,...]);
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)
}
我有一个使用 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
中的上一个状态。我该如何解决这个问题?
提前致谢。
据我所知,你的状态在 react-hooks 中过时了(被闭包捕获)。
那么你有这些解决方案:
1-useEffect
具有依赖项
useEffect(() => {
// state will be updated here
// declare 'customDispatch' here
}, [state,...]);
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)
}