首页 > 解决方案 > 显示 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 检查一样?

标签: javascriptreactjsreduxuse-reducer

解决方案


只需创建自己的日志记录功能。

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

编辑 new-moon-0g3zd


推荐阅读