gpt4 book ai didi

reactjs - 如何在自定义钩子(Hook)函数内访问 useReducer 的新状态

转载 作者:行者123 更新时间:2023-12-02 19:40:06 25 4
gpt4 key购买 nike

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

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];
}

使用自定义 Hook :

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

// for example use dispatch on click a button

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

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

提前致谢。

最佳答案

据我所知,你的状态在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)
}

关于reactjs - 如何在自定义钩子(Hook)函数内访问 useReducer 的新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60390358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com