import { useReducer } from "react"
// 申明初始数据
const initialState = {
counter: 100
}
// 定义ts类型
type ACTIONTYPES =
| { type: "increment", payload: number }
| { type: "decrement", payload: number }
// 定义类型处理函数
function counterReducer(state: typeof initialState, action: ACTIONTYPES) {
// function counterReducer(state, action) {
switch (action.type) {
case "increment":
return {
...state,
counter: state.counter + action.payload
}
case "decrement":
return {
...state,
counter: state.counter - action.payload
}
default:
throw new Error("什么鬼操作!")
}
}
// 创建reducer函数,将上面的处理函数和初始值放入参数
function UseReducerComponent() {
const [state, dispatch] = useReducer(counterReducer, initialState);
return (
<div>
<div>{state.counter}</div>
<div>
<button onClick={() => {
dispatch({
type: "increment",
payload: 10
})
}}>increment</button>
<button onClick={() => {
dispatch({
type: "decrement",
payload: 5
})
}}>decrement</button>
</div>
</div>
)
}
export default UseReducerComponent
网友评论