讓 React 管理多個相對關聯的狀態數據
import { useReducer } from "react"
// 1. 定義reducer函數,根據不同的action返回不同的狀態
function reducer(state, action) {switch (action.type) {case 'ADD':return state + action.payloadcase 'SUB':return state - 1default:return state}
}function App() {// 2. 組件中調用 useReducer, 0 是初始化參數const [state, dispatch] = useReducer(reducer, 0)return (<div className="App">{state}{/* 3. 調用dispatch 產生一個新的狀態,匹配事件(可傳參) 更新 UI */}<button onClick={() => { dispatch({ type: 'ADD', payload:100 }) }}>+</button><button onClick={() => { dispatch({ type: 'SUB' }) }}>-</button></div>)
}export default App;