使用useReducer + useContext 代替 react-redux

一. 概述

在 React16.8推出之前,我們使用react-redux并配合一些中間件,來(lái)對(duì)一些大型項(xiàng)目進(jìn)行狀態(tài)管理,React16.8推出后,我們普遍使用函數(shù)組件來(lái)構(gòu)建我們的項(xiàng)目,React提供了兩種Hook來(lái)為函數(shù)組件提供狀態(tài)支持,一種是我們常用的useState,另一種就是useReducer, 其實(shí)從代碼底層來(lái)看useState實(shí)際上執(zhí)行的也是一個(gè)useReducer,這意味著useReducer是更原生的,你能在任何使用useState的地方都替換成使用useReducer.

Reducer的概念是伴隨著Redux的出現(xiàn)逐漸在JavaScript中流行起來(lái)的,useReducer從字面上理解這個(gè)是reducer的一個(gè)Hook,那么能否使用useReducer配合useContext 來(lái)代替react-redux來(lái)對(duì)我們的項(xiàng)目進(jìn)行狀態(tài)管理呢?答案是肯定的。

二. useReducer 與 useContext

1. useReducer

在介紹useReducer這個(gè)Hook之前,我們先來(lái)回顧一下Reducer,簡(jiǎn)單來(lái)說(shuō) Reducer是一個(gè)函數(shù)(state, action) => newState:它接收兩個(gè)參數(shù),分別是當(dāng)前應(yīng)用的state和觸發(fā)的動(dòng)作action,它經(jīng)過(guò)計(jì)算后返回一個(gè)新的state.來(lái)看一個(gè)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('存在這個(gè)了值了')
                    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

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

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

useReducer 接受兩個(gè)參數(shù):第一個(gè)是上面我們介紹的reducer,第二個(gè)參數(shù)是初始化的state,返回的是個(gè)數(shù)組,數(shù)組第一項(xiàng)是當(dāng)前最新的state,第二項(xiàng)是dispatch函數(shù),它主要是用來(lái)dispatch不同的Action,從而觸發(fā)reducer計(jì)算得到對(duì)應(yīng)的state.

利用上面創(chuàng)建的reducer,看下如何使用useReducer這個(gè)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 className="example" style={{ color: state.themeColor, fontSize: state.themeFontSize }}>
      ReducerExamplePage
      <div>
        <input type="text" ref={inputRef}></input>
        <button onClick={addTodo}>增加</button>
        <div className="example-list">
          {
            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,會(huì)被認(rèn)為是只讀的 */}
            <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利用上面創(chuàng)建的todoReducer與初始狀態(tài)initState完成了初始化。用戶觸發(fā)增加、刪除、更新操作后,通過(guò)dispatch派發(fā)不類型的Actionreducer根據(jù)接收到的不同Action,調(diào)用各自邏輯,完成對(duì)state的處理后返回新的state。

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

那是不是可以使用useReducer來(lái)代替react-redux了呢?我們知道react-redux可以利用connect函數(shù),并且使用Provider來(lái)對(duì)<App />進(jìn)行了包裹,可以使任意組件訪問(wèn)store的狀態(tài)。

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

如果想要useReducer到達(dá)類似效果,我們需要用到useContext這個(gè)Hook。

2. useContext

useContext顧名思義,它是以Hook的方式使用React Context。先簡(jiǎn)單介紹 Context
Context設(shè)計(jì)目的是為了共享那些對(duì)于一個(gè)組件樹(shù)而言是“全局”的數(shù)據(jù),它提供了一種在組件之間共享值的方式,而不用顯式地通過(guò)組件樹(shù)逐層的傳遞props

const value = useContext(MyContext);

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

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創(chuàng)建了context,然后用ThemeContext.Provider標(biāo)簽包裹需要進(jìn)行狀態(tài)共享的組件樹(shù),在子組件中使用useContext獲取到value值進(jìn)行使用。

利用useReduceruseContext這兩個(gè)Hook就可以實(shí)現(xiàn)對(duì)react-redux的替換了。

三. 代替方案

通過(guò)一個(gè)例子看下如何利用useReducer+useContext代替react-redux,實(shí)現(xiàn)下面的效果:

pic

react-redux實(shí)現(xiàn)

這里假設(shè)你已經(jīng)熟悉了react-redux的使用,如果對(duì)它不了解可以去 查看.使用它來(lái)實(shí)現(xiàn)上面的需求:

  • 首先項(xiàng)目中導(dǎo)入我們所需類庫(kù)后,創(chuàng)建Store

    Store/index.tsx

    import { createStore,compose,applyMiddleware } from 'redux';
    import reducer from './reducer';
    import thunk from 'redux-thunk';// 配置 redux-thunk
    
    const composeEnhancers = compose;
    const store = createStore(reducer,composeEnhancers(
        applyMiddleware(thunk)// 配置 redux-thunk
    ));
    export type RootState = ReturnType<typeof store.getState>
    export default store;
    
  • 創(chuàng)建reduceractionCreator

    reducer.tsx

    import { ACTION_TYPE, IAction, IStore, ITodo } from "../../ReducerExample/type";
    
    const defaultState:IStore = {
        todoList:[],
        themeColor: '',
        themeFontSize: 14
    };
    const todoReducer = (state: IStore = defaultState, 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('存在這個(gè)了值了')
                        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
                        }
                    })
                }
            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
    

    actionCreator.tsx

    import {ACTION_TYPE, IAction } from "../../ReducerExample/type"
    import { Dispatch } from "redux";
    
    export const addCount = (val: string):IAction => ({
       type: ACTION_TYPE.ADD_TODO,
       payload:val
    })
    export const removeCount = (id: number):IAction => ({
       type: ACTION_TYPE.REMOVE_TODO,
       payload:id
    })
    export const upDateCount = (id: number):IAction => ({
       type: ACTION_TYPE.UPDATE_TODO,
       payload:id
    })
    export const changeThemeColor = (color: string):IAction => ({
       type: ACTION_TYPE.CHANGE_COLOR,
       payload:color
    })
    export const changeThemeFontSize = (fontSize: number):IAction => ({
       type: ACTION_TYPE.CHANGE_FONT_SIZE,
       payload:fontSize
    })
    export const asyncAddCount = (val: string) => {
       console.log('val======',val);
    
       return (dispatch:Dispatch) => {
           Promise.resolve().then(() => {
               setTimeout(() => {
                   dispatch(addCount(val))
                }, 2000);  
           })
       }
    
    }
    

最后我們?cè)诮M件中通過(guò)useSelector,useDispatch這兩個(gè)Hook來(lái)分別獲取state以及派發(fā)action

const todoList = useSelector((state: RootState) => state.newTodo.todoList)
const dispatch = useDispatch()
......
useReducer + useContext 實(shí)現(xiàn)

為了實(shí)現(xiàn)修改顏色與字號(hào)的需求,在最開(kāi)始的useReducer我們?cè)偬砑觾煞Naction類型,完成后的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: // 修改字號(hào)
            return {
                ...state,
                themeFontSize: payload
            }
        default:
            return state
    }
}
export default todoReducer

在父組件中創(chuàng)建Context,并將需要與子組件共享的數(shù)據(jù)傳遞給Context.ProviderValue prop

const initState: IStore = {
  todoList: [],
  themeColor: 'black',
  themeFontSize: 14
}
// 創(chuàng)建 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 className="example">
        ReducerExamplePage
        <div>
          <input type="text" ref={inputRef}></input>
          <button onClick={addTodo}>增加</button>
          <div className="example-list">
            {
              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}>改變字號(hào)</button>
        </div>
      </div>
    </ThemeContext.Provider>
  )
}
export default memo(ReducerExamplePage)

然后在ListItem中使用const theme = useContext(ThemeContext); 獲取傳遞的顏色與字號(hào),并進(jìn)行樣式綁定

    // 引入創(chuàng)建的context
    import { ThemeContext } from '../../ReducerExample/index'
    ...
    // 獲取傳遞的數(shù)據(jù)
    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結(jié)合useContext,通過(guò)Contextstate數(shù)據(jù)給組件樹(shù)中的所有組件使用 ,而不用通過(guò)props添加回調(diào)函數(shù)的方式一層層傳遞,達(dá)到了數(shù)據(jù)共享的目的。

四. 總結(jié)

總體來(lái)說(shuō),相比react-redux而言,使用useReducer + userContext 進(jìn)行狀態(tài)管理更加簡(jiǎn)單,免去了導(dǎo)入各種狀態(tài)管理庫(kù)以及中間鍵的麻煩,也不需要再創(chuàng)建storeactionCreator,對(duì)于新手來(lái)說(shuō),減輕了狀態(tài)管理的難度。對(duì)于一些小型項(xiàng)目完全可以用它來(lái)代替react-redux,當(dāng)然一些大型項(xiàng)目普遍還是使用react-redux來(lái)進(jìn)行的狀態(tài)管理,所以深入學(xué)習(xí)Redux 也是很有必要的。

一些參考:

React

React Redux

用useState還是用useReducer

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容