【发布时间】:2020-02-25 08:29:19
【问题描述】:
我有一个使用 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 内部的 prev 状态。我该如何解决这个问题?
提前致谢。
【问题讨论】:
标签: reactjs react-hooks use-reducer