<style> .description{ letter-spacing : 2px; line-height : 28px; text-align : justify; } .firstLine{ margin-left : 30px; } b{ font-weight : 700; } </style> # React useReducer [影片](https://www.youtube.com/watch?v=1Pks5cmfr4A) <div class="description"> useReducer和useState類似,都是用來改變State的Hook,但要是State數量變多的話會變得難以管理,而useReducer能讓我們方便管理數個State。<br><br> useReducer會給予我們兩個值,一個是State,用於管理所有State用,一個是dispatch,透過dispatch我們能直接更改State。 </div> ```javascript= import { useReducer } from "react"; function App() { const [state, dispatch] = useReducer(reducer, { name: "", age: 0, }); const clickHandler = () => { dispatch({ type: "SET_NAME" , name : "weiwei" }); }; return ( <> {state.name} // output: start : "" <button onClick={clickHandler}>Click</button> </> ); } export default App; ``` <div class="description"> 但在使用useReducer前,我們必須先定義自己的Reducer Function,先透過以下範例來看如何定義Reducer。 reducer所包含的參數有<b>state</b>和<b>action</b>。 </div> reducer : state : state為我們使用useReducer時,初定義的state,由以上程式碼來看的話,我們的初定義的state是,<b>name和age</b>,所以我們可以利用參數state來去訪問我們的state內容。 reducer : action : action較常用的就是接收外部資料,<b>如果想透過外部資料來改變state時可以用action來取得資料</b>,同時在定義時也常用action.type來去取得dispatch的type為何,然後用switch case來去做後續更改state的動作。 ```javascript= const reducer = (state, action) => { switch (action.type) { case "SET_NAME": return { name : action.name, age : 0 }; default: return state; } }; ``` <div class="description"> 定義好reducer function後,就可以直接來使用啦! </div> ```javascript= import { useReducer } from "react"; const reducer = (state, action) => { //console.log(action) output : {type : "SET_NAME" , name : "weiwei"} switch (action.type) { case "SET_NAME": return { //這邊可以選擇利用其餘參數 ...state 來把age帶入 因為不會動到age name : action.name, age : 0 }; default: return state; } }; function App() { const [state, dispatch] = useReducer(reducer, { name: "", age: 0, }); const clickHandler = () => { dispatch({ type: "SET_NAME" , name : "weiwei" }); }; return ( <> {state.name} // output: start : "" | after click : weiwei <button onClick={clickHandler}>Click</button> </> ); } export default App; ```