美文网首页
关于hooks中reducer的使用

关于hooks中reducer的使用

作者: 中華小龍 | 来源:发表于2021-11-24 12:43 被阅读0次
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

相关文章

网友评论

      本文标题:关于hooks中reducer的使用

      本文链接:https://www.haomeiwen.com/subject/wwyntrtx.html