javascript - React Hooks - useReducer:在触发函数之前等待减速器完成
问题描述
我有使用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
钩子:
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" });
}
推荐阅读
- node.js - 使用 NextJS 和 next-i18next 进行 Fastify - res.header 不是函数
- java - java - 如何在java中正确地使客户端服务器说话?
- python - Neo4j csv 数据摄取节点被复制
- c# - Git自动合并在挑选樱桃时删除了一些信息
- javascript - document.getElementById(...) 在javascript中为空
- apache-spark - 带有火花结构流数据的 Azure eventhub
- amazon-web-services - 新 AWS Gateway UI 的映射模板
- android - 如何减少Android中Workmanager的时间段?
- python - 如何使用正则表达式从字符串中获取特定数字部分
- c# - 这个对象初始化有什么区别