useReducer 介绍
const [state, dispatch] = React.useReducer(reducer, initialArg, init);
useReducer
是useState
的替代方案- 接收:如
(state, action)=>newState
的 reducer - 返回:当前
state
和 dispatch
方法
useReducer
使用场景:- state 逻辑复杂且包含多个子值
- 下一个 state 依赖于之前的 state
useReducer 使用
import React, { useReducer } from 'react';
const initState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + action.payload }
case "decrement":
return { count: state.count - action.payload }
default:
return state;
}
}
function App() {
const [state, dispatch] = useReducer(reducer, initState);
return (
<div>
<h2>useReducer</h2>
{}
count :{state.count}
<button onClick={() => dispatch({ type: "increment", payload: 3 })}>+</button>
</div>
)
}
export default App;