😸 學習使用 useReducer
import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
// ...
做一個點選功能鍵後會把畫面上的數值 + 1
我們先以 useReducer
建立狀態,並且預設狀態是 num:15
export default function Counter() {
const [state, dispatch] = useReducer(reducer, { num: 15 });
return (
...
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, { num: 15 });
return (
<>
<h1>React 大秘境 DAY 16</h1>
<button
onClick={() => {
dispatch({ type: "addNum" });
}}
>
點我 +1
</button>
<p>團購 + {state.num} .</p>
</>
);
}
function reducer(state, action) {
// console.log(action);
if (action.type === "addNum") {
return {
num: state.num + 1
};
}
throw Error("不存在");
}
看看結果
![img][https://i.imgur.com/Wc5tFbB.gif)
😸 透過 useReducer 可以讓狀態有比較複雜的變化,我們下個任務見!