一. 概述
在 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: numbercontent: stringcomplete: 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 } = actionswitch (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 statecase 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 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
}
constListItem:React.FC<IProps> = ({todo,updateTodo,removeTodo
}) : ReactElement => {const {id, content, complete} = todoreturn (<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
派發不類型的
Action
,
reducer
根據接收到的不同
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
。先簡單介紹
Context
。
Context
設計目的是為了共享那些對于一個元件樹而言是**“全局”**的資料,它提供了一種在元件之間共享值的方式,而不用顯式地通過元件樹逐層的傳遞
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
值進行使用。
利用
useReducer
、
useContext
這兩個Hook就可以實作對
react-redux
的替換了。
三. 代替方案
通過一個例子看下如何利用
useReducer
+
useContext
代替
react-redux
,實作下面的效果:
react-redux
實作
react-redux
這裡假設你已經熟悉了
react-redux
的使用,如果對它不了解可以去 檢視.使用它來實作上面的需求:
- 首先項目中導入我們所需類庫後,建立
reducerStore``Store/index.tsx````import { createStore,compose,applyMiddleware } from 'redux';import reducer from './reducer';import thunk from 'redux-thunk';// 配置 redux-thunkconst composeEnhancers = compose;const store = createStore(reducer,composeEnhancers(applyMiddleware(thunk)// 配置 redux-thunk));export type RootState = ReturnType<typeof store.getState>export default store; ```* 建立
actionCreator``reducer.tsx與
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); }) }} ```最後我們在元件中通過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 } = actionswitch (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 statecase 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
這兩個Hook來分别擷取useSelector,useDispatch
以及派發state
:action
const todoList = useSelector((state: RootState) => state.newTodo.todoList)
const dispatch = useDispatch()
......
useReducer
+ useContext
實作
useReducer
useContext
為了實作修改顔色與字号的需求,在最開始的
useReducer
我們再添加兩種
action
類型,完成後的
reducer
:
const todoReducer = (state: IStore, action: IAction): IStore => {const { type, payload } = actionswitch (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.Provider
的
Value 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 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}>改變字号</button></div></div></ThemeContext.Provider>)
}
export default memo(ReducerExamplePage)
然後在
ListItem
中使用
const theme = useContext(ThemeContext);
擷取傳遞的顔色與字号,并進行樣式綁定
// 引入建立的contextimport { 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
,通過
Context
把
state
資料給元件樹中的所有元件使用 ,而不用通過
props
添加回調函數的方式一層層傳遞,達到了資料共享的目的。
最後
整理了一套《前端大廠面試寶典》,包含了HTML、CSS、JavaScript、HTTP、TCP協定、浏覽器、VUE、React、資料結構和算法,一共201道面試題,并對每個問題作出了回答和解析。
有需要的小夥伴,可以點選文末卡片領取這份文檔,無償分享
部分文檔展示:
文章篇幅有限,後面的内容就不一一展示了
有需要的小夥伴,可以點下方卡片免費領取