使用 useReducer - useContext 代替 react-redux

本文作者爲奇舞團前端開發工程師

一. 概述

在 React16.8 推出之前,我們使用react-redux並配合一些中間件,來對一些大型項目進行狀態管理,React16.8 推出後,我們普遍使用函數組件來構建我們的項目,React 提供了兩種 Hook 來爲函數組件提供狀態支持,一種是我們常用的useState, 另一種就是useReducer, 其實從代碼底層來看useState實際上執行的也是一個useReducer, 這意味着useReducer是更原生的,你能在任何使用useState的地方都替換成使用useReducer.

Reducer的概念是伴隨着Redux的出現逐漸在 JavaScript 中流行起來的,useReducer從字面上理解這個是reducer的一個 Hook,那麼能否使用useReducer配合useContext 來代替react-redux來對我們的項目進行狀態管理呢?答案是肯定的。

二. useReducer 與 useContext

1. useReducer

在介紹useReducer這個 Hook 之前,我們先來回顧一下Reducer,簡單來說 Reducer是一個函數(state, action) => newState:它接收兩個參數,分別是當前應用的state和觸發的動作action,它經過計算後返回一個新的state. 來看一個todoList的例子:

export interface ITodo {
    id: number
    content: string
    complete: boolean
}

export interface IStore {
    todoList: ITodo[],
}

export interface IAction {
    type: string,
    payload: any
}

export enum ACTION_TYPE {
    ADD_TODO = 'addTodo',
    REMOVE_TODO = 'removeTodo',
    UPDATE_TODO = 'updateTodo',
}

import { ACTION_TYPE, IAction, IStore, ITodo } from "./type";

const todoReducer = (state: IStore, action: IAction): IStore => {
    const { type, payload } = action
    switch (type) {
        case ACTION_TYPE.ADD_TODO: //增加
            if (payload.length > 0) {
                const isExit = state.todoList.find(todo => todo.content === payload)
                if (isExit) {
                    alert('存在這個了值了')
                    return state
                }
                const item = {
                    id: new Date().getTime(),
                    complete: false,
                    content: payload
                }
                return {
                    ...state,
                    todoList: [...state.todoList, item as ITodo]
                }
            }
            return state
        case ACTION_TYPE.REMOVE_TODO:  // 刪除 
            return {
                ...state,
                todoList: state.todoList.filter(todo => todo.id !== payload)
            }
        case ACTION_TYPE.UPDATE_TODO: // 更新
            return {
                ...state,
                todoList: state.todoList.map(todo => {
                    return todo.id === payload ? {
                        ...todo,
                        complete: !todo.complete
                    } : {
                        ...todo
                    }
                })
            }
        default:
            return state
    }
}
export default todoReducer

上面是個 todoList 的例子,其中reducer可以根據傳入的action類型(ACTION_TYPE.ADD_TODO、ACTION_TYPE.REMOVE_TODO、UPDATE_TODO)來計算並返回一個新的 state。reducer本質是一個純函數,沒有任何 UI 和副作用。接下來看下useReducer:

 const [state, dispatch] = useReducer(reducer, initState);

useReducer 接受兩個參數:第一個是上面我們介紹的reducer,第二個參數是初始化的state,返回的是個數組,數組第一項是當前最新的 state,第二項是dispatch函數, 它主要是用來 dispatch 不同的Action,從而觸發reducer計算得到對應的state.

利用上面創建的reducer, 看下如何使用useReducer這個 Hook:

const initState: IStore = {
  todoList: [],
  themeColor: 'black',
  themeFontSize: 16
}

const ReducerExamplePage: React.FC = (): ReactElement => {
  const [state, dispatch] = useReducer(todoReducer, initState)
  const inputRef = useRef<HTMLInputElement>(null);

  const addTodo = () => {
    const val = inputRef.current!.value.trim()
    dispatch({ type: ACTION_TYPE.ADD_TODO, payload: val })
    inputRef.current!.value = ''
  }
  
  const removeTodo = useCallback((id: number) => {
    dispatch({ type: ACTION_TYPE.REMOVE_TODO, payload: id })
  }, [])

  const updateTodo = useCallback((id: number) => {
    dispatch({ type: ACTION_TYPE.UPDATE_TODO, payload: id })
  }, [])

  return (
    <div class style={{ color: state.themeColor, fontSize: state.themeFontSize }}>
      ReducerExamplePage
      <div>
        <input type="text" ref={inputRef}></input>
        <button onClick={addTodo}>增加</button>
        <div class>
          {
            state.todoList && state.todoList.map((todo: ITodo) => {
              return (
                <ListItem key={todo.id} todo={todo} removeTodo={removeTodo} updateTodo={updateTodo} />
              )
            })
          }
        </div>
      </div>
    </div>
  )
}
export default ReducerExamplePage

ListItem.tsx

import React, { ReactElement } from 'react';
import { ITodo } from '../typings';

interface IProps {
    todo:ITodo,
    removeTodo: (id:number) => void,
    updateTodo: (id: number) => void
}
const  ListItem:React.FC<IProps> = ({
    todo,
    updateTodo,
    removeTodo
}) : ReactElement => {
    const {id, content, complete} = todo
    return (
        <div> 
            {/* 不能使用onClick,會被認爲是隻讀的 */}
            <input type="checkbox" checked={complete} onChange = {() => updateTodo(id)}></input>
            <span style={{textDecoration:complete?'line-through' : 'none'}}>
                {content}
            </span>
            <button onClick={()=>removeTodo(id)}>
                刪除
            </button>
        </div>
    );
}
export default ListItem;

useReducer利用上面創建的todoReducer與初始狀態initState完成了初始化。用戶觸發增加、刪除、更新操作後,通過dispatch派發不類型的Actionreducer根據接收到的不同Action,調用各自邏輯,完成對 state 的處理後返回新的 state。

可以看到useReducer的使用邏輯,幾乎跟react-redux的使用方式相同,只不過react-redux中需要我們利用actionCreator來進行 action 的創建,以便利用Redux中間鍵 (如redux-thunk) 來處理一些異步調用。

那是不是可以使用useReducer來代替react-redux了呢?我們知道react-redux可以利用connect函數,並且使用Provider來對<App />進行了包裹,可以使任意組件訪問 store 的狀態。

 <Provider store={store}>
   <App />
 </Provider>

如果想要useReducer到達類似效果,我們需要用到useContext這個 Hook。

2. useContext

useContext顧名思義,它是以 Hook 的方式使用React Context。先簡單介紹 ContextContext設計目的是爲了共享那些對於一個組件樹而言是 “全局” 的數據, 它提供了一種在組件之間共享值的方式,而不用顯式地通過組件樹逐層的傳遞props

const value = useContext(MyContext);

useContext: 接收一個context對象(React.createContext 的返回值)並返回該context的當前值, 當前的 context值由上層組件中距離當前組件最近的<MyContext.Provider>value prop 決定。來看官方給的例子:

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

const ThemeContext = React.createContext(themes.light);

function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  );
}

上面的例子,首先利用React.createContext創建了context, 然後用ThemeContext.Provider標籤包裹需要進行狀態共享的組件樹,在子組件中使用useContext獲取到value值進行使用。

利用useReduceruseContext這兩個 Hook 就可以實現對react-redux的替換了。

三. 代替方案

通過一個例子看下如何利用useReducer+useContext代替react-redux, 實現下面的效果:

react-redux實現

這裏假設你已經熟悉了react-redux的使用,如果對它不瞭解可以去 查看. 使用它來實現上面的需求:

最後我們在組件中通過useSelector,useDispatch這兩個 Hook 來分別獲取state以及派發action

const todoList = useSelector((state: RootState) => state.newTodo.todoList)
const dispatch = useDispatch()
......
useReducer + useContext 實現

爲了實現修改顏色與字號的需求,在最開始的useReducer我們再添加兩種action類型,完成後的reducer:

const todoReducer = (state: IStore, action: IAction): IStore => {
    const { type, payload } = action
    switch (type) {
        ...
        case ACTION_TYPE.CHANGE_COLOR: // 修改顏色
            return {
                ...state,
                themeColor: payload
            }
        case ACTION_TYPE.CHANGE_FONT_SIZE: // 修改字號
            return {
                ...state,
                themeFontSize: payload
            }
        default:
            return state
    }
}
export default todoReducer

在父組件中創建Context, 並將需要與子組件共享的數據傳遞給Context.ProviderValue prop

const initState: IStore = {
  todoList: [],
  themeColor: 'black',
  themeFontSize: 14
}
// 創建 context
export const ThemeContext = React.createContext(initState);

const ReducerExamplePage: React.FC = (): ReactElement => {
  ...
  
  const changeColor = () => {
    dispatch({ type: ACTION_TYPE.CHANGE_COLOR, payload: getColor() })
  }

  const changeFontSize = () => {
    dispatch({ type: ACTION_TYPE.CHANGE_FONT_SIZE, payload: 20 })
  }

  const getColor = (): string => {
    const x = Math.round(Math.random() * 255);
    const y = Math.round(Math.random() * 255);
    const z = Math.round(Math.random() * 255);
    return 'rgb(' + x + ',' + y + ',' + z + ')';
  }

  return (
    // 傳遞state值
    <ThemeContext.Provider value={state}>
      <div class>
        ReducerExamplePage
        <div>
          <input type="text" ref={inputRef}></input>
          <button onClick={addTodo}>增加</button>
          <div class>
            {
              state.todoList && state.todoList.map((todo: ITodo) => {
                return (
                  <ListItem key={todo.id} todo={todo} removeTodo={removeTodo} updateTodo={updateTodo} />
                )
              })
            }
          </div>
          <button onClick={changeColor}>改變顏色</button>
          <button onClick={changeFontSize}>改變字號</button>
        </div>
      </div>
    </ThemeContext.Provider>
  )
}
export default memo(ReducerExamplePage)

然後在ListItem中使用const theme = useContext(ThemeContext); 獲取傳遞的顏色與字號,並進行樣式綁定

    // 引入創建的context
    import { ThemeContext } from '../../ReducerExample/index'
    ...
    // 獲取傳遞的數據
    const theme = useContext(ThemeContext);
     
    return (
        <div>
            <input type="checkbox" checked={complete} onChange={() => updateTodo(id)} style={{ color: theme.themeColor, fontSize: theme.themeFontSize }}></input>
            <span style={{ textDecoration: complete ? 'line-through' : 'none', color: theme.themeColor, fontSize: theme.themeFontSize }}>
                {content}
            </span>
            <button onClick={() => removeTodo(id)} style={{ color: theme.themeColor, fontSize: theme.themeFontSize }}>
                刪除
            </button>
        </div>
    );

可以看到在useReducer結合useContext,通過Contextstate數據給組件樹中的所有組件使用 ,而不用通過props添加回調函數的方式一層層傳遞, 達到了數據共享的目的。

四. 總結

總體來說,相比react-redux而言,使用useReducer + userContext 進行狀態管理更加簡單,免去了導入各種狀態管理庫以及中間鍵的麻煩,也不需要再創建storeactionCreator,對於新手來說,減輕了狀態管理的難度。對於一些小型項目完全可以用它來代替react-redux,當然一些大型項目普遍還是使用react-redux來進行的狀態管理,所以深入學習Redux 也是很有必要的。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/CzgM90pxubNwAnAArdDHYw