熟悉 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几乎一模一样。