React Hooks - useReducer:在触发函数之前等待减速器完成

Trí*_*han 7 javascript reactjs react-hooks

我有使用useReducerHooks的组件:

const init = {
  statA: true,
  statB: true
};

const reducer = (state, action) => {
  switch (action.type) {
    case "ActionA":
      return { ...state, statA: !state.statA };
    case "ActionB":
      return { ...state, statB: !state.statB };
    default:
      return state;
  }
};

const App = () => {
  const [state, dispatch] = useReducer(reducer, init);

  const clickMe = () => {
    dispatch({ type: "ActionA" });
    dispatch({ type: "ActionB" });
    console.log(state);
  }

  return(
      <button onClick={() => clickMe()}>Click Me</button>
  );
};
Run Code Online (Sandbox Code Playgroud)

单击按钮时,状态将更改。但是当我查看日志时,它会打印之前的状态,而不是当前更新的状态。

//On the first click
//Expected
{ statA: false, statB: false }
//Reality
{ statA: true, statB: true }

//On the second click
//Expected
{ statA: true, statB: true }
//Reality
{ statA: false, statB: false }
Run Code Online (Sandbox Code Playgroud)

我知道使用setState,我可以使用回调来处理更新的状态。但是对于useReducer,我不知道如何处理更新的状态。有什么办法可以解决我的问题吗?

Est*_*ask 9

console.log(state)是副作用。副作用属于useEffecthook:

  const [state, dispatch] = useReducer(reducer, init);

  useEffect(() => {
    // a condition may be added in case it shouldn't be executed every time
    console.log(state);
  }, [state]);

  const clickMe = () => {
    dispatch({ type: "ActionA" });
    dispatch({ type: "ActionB" });
  }
Run Code Online (Sandbox Code Playgroud)