useReducer使用

熟悉 redux 的同学都知道,在 redux 中,状态并不直接更改,而是通过发起 action 给状态管理器,收到 action 后,使用 reducer 计算出新的状态,即(state, action) => newState。

useReducer()也是一样的,const [state,dispatch] = useReducer(reducer, initialState),它接收一个形如(state, action) => newState的 reducer,并返回当前 state 以及发起 action 的 dispath 方法。

以下是用useReducer实现了一个基数Demo:

import { useReducer } from "react";

const initState = {
  num: 0,
};

interface initStateType {
  num: number;
}

interface actionType {
  type: string;
}

const numReducer = (state: initStateType, action: actionType) => {
  switch (action.type) {
    case "add":
      return { ...state, num: state.num + 1 };
    case "reduce":
      return { ...state, num: state.num - 1 };
    default:
      return state;
  }
};

const Example = () => {
  const [state, dispatch] = useReducer(numReducer, initState);
  return (
    <div style={{ textAlign: "center", marginTop: 50 }}>
      <div>数量: {state.num}</div>
      <button onClick={() => dispatch({ type: "reduce" })}>减少</button>
      <button onClick={() => dispatch({ type: "add" })}>增加</button>
    </div>
  );
};

export default Example;

使用方法和redux几乎一模一样。


效果图
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容