gpt4 book ai didi

javascript - React Hooks - 使用Reducer : Wait for reducer to finish before triggering a function

转载 作者:行者123 更新时间:2023-11-30 09:15:14 25 4
gpt4 key购买 nike

我有使用 useReducer Hooks 的组件:

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

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

//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 }

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

最佳答案

console.log(state) 是副作用。副作用属于 useEffect 钩子(Hook):

  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" });
}

关于javascript - React Hooks - 使用Reducer : Wait for reducer to finish before triggering a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55559307/

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