useReducer 与复杂状态
约 333 字大约 1 分钟
布欧-Lewyon
2026-05-15
useReducer 基础
import { useReducer } from 'react'
// 1. 定义状态类型
interface CounterState {
count: number
step: number
}
// 2. 定义 Action 类型
type CounterAction =
| { type: 'INCREMENT' }
| { type: 'DECREMENT' }
| { type: 'SET_STEP'; payload: number }
| { type: 'RESET' }
// 3. Reducer 函数
function counterReducer(state: CounterState, action: CounterAction): CounterState {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + state.step }
case 'DECREMENT':
return { ...state, count: state.count - state.step }
case 'SET_STEP':
return { ...state, step: action.payload }
case 'RESET':
return { count: 0, step: 1 }
default:
return state
}
}
// 4. 使用
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0, step: 1 })
return (
<div>
<p>Count: {state.count}</p>
<input
type="number"
value={state.step}
onChange={e => dispatch({ type: 'SET_STEP', payload: +e.target.value })}
/>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
<button onClick={() => dispatch({ type: 'RESET' })}>Reset</button>
</div>
)
}useState vs useReducer
| 对比 | useState | useReducer |
|---|---|---|
| 复杂度 | 简单状态 | 复杂状态逻辑 |
| 状态关联 | 多个独立 state | 相关字段集中管理 |
| 可测试性 | 一般 | ✅ Reducer 纯函数易测试 |
| 可读性 | 好 | 清晰(Action 名称化) |
选择标准:当状态包含多个子值或状态更新逻辑复杂时,用 useReducer。
小结
useReducer(reducer, initialState)返回[state, dispatch]。- Reducer 是纯函数
(state, action) => newState。 - Action 是
{ type, payload }对象,type 描述操作类型。 - 适合表单、购物车、复杂多步骤状态管理。
- Reducer 纯函数,可脱离 React 单独测试。
