1. 程式人生 > 實用技巧 >React函式式元件值之useContext()和useReducer()

React函式式元件值之useContext()和useReducer()

一、useContext

二、useReducer

  useReducer 類似 redux 中的功能,相較於 useState,它更適合一些邏輯較複雜且包含多個子值,或者下一個 state 依賴於之前的 state 等等的特定場景, useReducer 總共有三個引數

  • 第一個引數是 一個 reducer,就是一個函式類似 (state, action) => newState 的函式,傳入 上一個 state 和本次的 action
  • 第二個引數是初始 state,也就是預設值,是比較簡單的方法
  • 第三個引數是惰性初始化,這麼做可以將用於計算 state 的邏輯提取到 reducer 外部,這也為將來對重置 state 的 action 做處理提供了便利
 1 function reducer(state, action) {
 2   switch (action.type) {
 3     case 'increment':
 4       return {count: state.count + 1};
 5     case 'decrement':
 6       return {count: state.count - 1};
 7     default:
 8       throw new Error();
 9   }
10 }
11 function App() {
12   const [state, dispatch] = useReducer(reducer, {count: 0});
13   return (
14     <>
15       點選次數: {state.count}
16       <button onClick={() => dispatch({type: 'increment'})}>+</button>
17       <button onClick={() => dispatch({type: 'decrement'})}>-</button>
18     </>
19   );
20 }