useReducer 就像是 Vue 的 Vuex/Pinia,但是是组件级别的。当你的状态逻辑比较复杂时,useState 就不够用了,这时候 useReducer 就派上用场了。
import { useReducer } from 'react'
// 定义初始状态
const initialState = {
count: 0,
name: '用户'
}
// 定义 reducer 函数
function counterReducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + 1 }
case 'decrement':
return { ...state, count: state.count - 1 }
case 'reset':
return { ...state, count: 0 }
default:
return state
}
}
// 在组件中使用
function Counter() {
const [state, dispatch] = useReducer(counterReducer, initialState)
return (
<div>
<p>计数:{state.count}</p>
<p>用户:{state.name}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+1</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-1</button>
<button onClick={() => dispatch({ type: 'reset' })}>重置</button>
</div>
)
}
state也类似于vue中的state,是存放数据的地方。
适合用 useReducer 的场景:**状态逻辑复杂、****多个相关状态(**购物车的商品和总价)