基本用法
1 2 3 4
| const [products, setProducts] = useState(sampleData); const [ascending, setAscending] = useState(true); const [search, setSearch] = useState(''); const [items, setItems] = useState([]);
|
當有一些資料處理的是相關的邏輯時,如上都是和 products 有關的邏輯,可以用 useReducer 整合在一起
- 將 useReducer 方法解構出來
1
| const { useState, useReducer } = React;
|
- 建立資料和方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const App = () => { const [state, dispatch] = useReducer( function (state, action) { switch (action.type) { case 'INCREMENT': return { num: state.num + 1 } break; case 'DECREMENT': return { num: state.num - 1 } break; case 'SET_NUM': return { num: action.payload, } break; default: break; } return state; }, { num: 5 }, );
|
useReducer()
函式第一個參數會帶入一個函式,第二個參數則會帶入物件(定義資料),之後就可將 state, dispatch 解構出來給元件使用。
- 元件內使用 資料與方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| function increment() { dispatch({ type: 'INCREMENT', }) } function decrement() { dispatch({ type: 'DECREMENT', }) }
function setNum(e) { dispatch({ type: 'SET_NUM', payload: parseInt(e.target.value), }) } <button type="button" onClick={() => decrement() }>-</button> {state.num} <button type="button" onClick={() => increment() }>+</button> <input type="number" value={state.num} onChange={ e => setNum(e)} />
|
元件觸發事件後呼叫 dispatch 方法來修改 state 的值,type 指定事件名稱,如果有參數帶入,則放在 payload 裡。
實作範例
範例
上面範例將 products 相關狀態都整合進 useReducer裡。