useReducer
1. 说明
- useState 的替代方案。
- 它接收一个( 形如
(oldState, action) => newState
的) reducer,并返回当前的 state 以及与其配套的dispatch
方法。
2. 语法
###2.1 语法格式
const [state, dispatch] = useReducer(reducer, initial);
2.2 语法说明
- 参数 : 1-reducer 2-状态初始值
- 返回值 : 当前的 state 以及与其配套的
dispatch
方法。
3. 使用
3.1 重写 useState (计算器示例)
- 之前的 useState
import { useState } from 'react'
//2. 创建组件
const App = () => {
const [counter, setCounter] = useState(0)
return (
<div>
<div>函数组件 - {counter}</div>
<button onClick={() => setCounter(counter + 1)}>+1</button>
<button onClick={() => setCounter(counter - 1)}>+1</button>
</div>
)
}
- 改造的 useReducer
import { useReducer } from 'react'
// reducer
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
default:
return state
}
}
//2. 创建组件
const App = () => {
const [counter, dispatch] = useReducer(reducer, 10)
return (
<div>
<div>函数组件 - {counter}</div>
<button onClick={() => dispatch({ type: 'increment' })}>+1</button>
<button onClick={() => dispatch({ type: 'decrement' })}>+1</button>
</div>
)
}
3.2 useReducer 使用场景
- 在某些场景下,
useReducer
会比useState
更适用 : 例如 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
return state
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}