React Hooks - useReducer:在触发函数之前等待减速器完成 [英] React Hooks - useReducer: Wait for reducer to finish before triggering a function
本文介绍了React Hooks - useReducer:在触发函数之前等待减速器完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有使用 useReducer
钩子的组件:
I have the component using 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>
);
};
当按钮被点击时,状态将会改变.但是当我查看日志时,它打印的是以前的状态,而不是当前更新的状态.
When the button is clicked, the state will be changed. But when I view the log, it prints the previous state, not the current updated state.
//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
,我不知道如何处理更新的状态.有什么办法可以解决我的问题吗?
I know that with setState
, I can use callback to work with updated state. But with useReducer
, I don't know how to work with the updated state. Is there any way to solve my problem?
推荐答案
console.log(state)
是副作用.副作用属于 useEffect
钩子:
console.log(state)
is side effect. Side effects belong to 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" });
}
这篇关于React Hooks - useReducer:在触发函数之前等待减速器完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文