javascript - 显示 react reducer 操作,例如 redux devTool
问题描述
我已经reducer
使用 Reat 的useReducer
钩子创建了一个函数。
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + action.payload };
case 'decrement':
return { count: state.count - action.payload };
default:
throw new Error();
}
}
在一个组件内部-
const [state, dispatch] = useReducer(reducer, {count: 0});
现在,我在加载 API 数据后调度一个动作,例如 -
useEffect(() => {
(async () => {
const res = await fetch(some_url);
const data = await res.json();
dispatch({type: 'increment', payload: data});
)();
})
现在有什么方法可以检查动作{type: 'increment'}
是否被触发/调度,就像我们使用 redux DevTool 检查一样?
解决方案
只需创建自己的日志记录功能。
import { useReducer, useEffect } from "react";
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + action.payload };
case "decrement":
return { count: state.count - action.payload };
default:
throw new Error();
}
}
const addLoggingToDispatch = (dispatch, args) => {
console.log(args);
dispatch(args);
};
export default function App() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
useEffect(() => {
addLoggingToDispatch(dispatch, { type: "increment", payload: "data" });
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
推荐阅读
- r - 从 R 将文件上传到 SharePoint
- php - 使用其变量运行函数的更短方法
- javascript - Node.js:如何使用 url 参数从获取请求解析后响应 json 对象
- android - 每 16ms 间隔发送和接收 TCP 数据
- c++ - Qt + conan = 使用空输出设备,无可用
- php - 删除换行符的问题
- object-detection-api - 如何删除检测分数(百分比)?
- android - 无法在 TextEdit 或任何其他编辑字段中键入希伯来字母
- symfony - Symfony Sonata Admin:如何从 DB 中获取选择数组
- c++ - 调用POCO c ++ ServerSocket()时Linux上的分段错误