主题
useReducer
基本使用
介绍
useReducer 是 React 提供的一个 Hook,用于在函数组件中管理复杂的状态逻辑。它类似于 Redux 的工作原理,但更轻量级,适合局部状态管理。
示例
jsx
import { useReducer } from 'react'
const INITIAL_STATE = { count: 0, step: 1 }
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + state.step }
case 'decrement':
return { ...state, count: state.count - state.step }
case 'reset':
return INITIAL_STATE
case 'setStep':
return { ...state, step: Math.max(1, Math.floor(action.payload)) }
default:
return state
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, INITIAL_STATE)
const { count, step } = state
return (
<section style={{ maxWidth: 360 }}>
<label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<span>当前步长</span>
<input
type="number"
min={1}
value={step}
onChange={(event) => {
const rawValue = Number(event.target.value)
const parsedValue = Number.isFinite(rawValue) && rawValue > 0 ? Math.floor(rawValue) : 1
dispatch({ type: 'setStep', payload: parsedValue })
}}
style={{ padding: '6px 8px' }}
/>
</label>
<div style={{ marginTop: 16 }}>
<p style={{ margin: '8px 0', fontSize: 24, fontWeight: 600 }}>Count: {count}</p>
<p style={{ margin: '4px 0', color: '#555' }}>每次加减 {step}</p>
</div>
<div style={{ display: 'flex', gap: 12, marginTop: 12 }}>
<button
onClick={() => {
dispatch({ type: 'decrement' })
}}
>
- 减少
</button>
<button
onClick={() => {
dispatch({ type: 'increment' })
}}
>
+ 增加
</button>
<button
onClick={() => {
dispatch({ type: 'reset' })
}}
>
重置
</button>
</div>
</section>
)
}
export default CounteruseReducer 相比于 useState 的优势
useState 非常适合处理简单、独立的状态,但在处理复杂逻辑时,可能会遇到:
- 状态关联复杂:多个
useState相互关联,更新逻辑散落在各处。 - 状态依赖严重:下一个状态的值严重依赖于前一个状态,逻辑难以追踪。
- 深层传递问题:将更新函数传递给深层子组件,可能导致不必要的重复渲染。
useReducer 并非 useState 的替代品,而是在特定复杂度下更优的解决方案。它会帮助我们:
- 集中管理状态逻辑。
- 状态逻辑与视图分离。
- 可预测的状态流与便捷的调试。
- 优化深层组件的性能。
