用ts重写React官方文档里的demo(2)——Hook API索引:useReducer

74 阅读1分钟
import { useReducer } from "react";

const initialState = {count: 0};

type CounterActionType = {
    type: string
}
type CounterStateType = {
    count: number
}


function reducer(state: CounterStateType, action: CounterActionType){
    switch (action?.type) {
        case 'increment':
            return {count: state.count + 1};
        case 'decrement':
            return {count: state.count - 1};
        default:
            throw new Error();
    }
}

function Counter() {
    const [state, dispatch] = useReducer(reducer, initialState)
    return (
        <>
            Count: {state.count}
            <button onClick={() => dispatch({type: 'increment'})}>+</button>
            <button onClick={() => dispatch({type: 'decrement'})}>-</button>
        </>
    )
}

export default Counter