useReducer
- 可以看成是useState的进化版本,集成式的处理数据
import { useReducer } from "react";
const PLUS = 'PLUS';
const MINUS = 'MINUS';
function UseReducer() {
function reducer(state, action) {
switch (action.type) {
case PLUS:
return state + 1;
case MINUS:
return state - 1;
default:
return state;
}
}
const [num, dispatch] = useReducer(reducer, 0);
return <div>
<h1>{ num }</h1>
<button onClick={() => dispatch({type: PLUS})}>+</button>
<button onClick={() => dispatch({type: MINUS})}>-</button>
</div>;
}
export default UseReducer;

示意图
/*
type <--- dispatch <--- useReducer
| |
| |
PLUS + 1 |
MINUS - 1 <-------- num <----
|
|/
reducer
*/