import { useState } from "react"
// useReducer,
// 統一排程
function reducer(state, action) {
console.log('reducer接收參數', state, action)
const { type } = action
switch (type) {
case 'add':
return { num: state.num + 1 }
case 'minus':
return { num: state.num - 1 }
}
}
function useReducer(reducer, initState) {
// initState用于初始化
const [state, setState] = useState(initState)
const dispatch = (action) => {
const newVal = reducer(state, action)
setState(newVal)
}
return [state, dispatch]
}
export default function App() {
// 參數:歸納函數,初始狀态
const [state, dispatch] = useReducer(reducer, { num: 0 })
return (
<>
<p>數:{state.num}</p>
<button onClick={() => dispatch({ type: 'add' })}>+1</button>
<br />
<button onClick={() => dispatch({ type: 'minus' })}>-1</button>
</>
)
}