一. 概述
在 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ā)不類型的Action
,reducer
根據(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)行使用。
利用useReducer
、useContext
這兩個(gè)Hook就可以實(shí)現(xiàn)對(duì)react-redux
的替換了。
三. 代替方案
通過(guò)一個(gè)例子看下如何利用useReducer
+useContext
代替react-redux
,實(shí)現(xiàn)下面的效果:
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)建
reducer
與actionCreator
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.Provider
的Value 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ò)Context
把state
數(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)建store
和actionCreator
,對(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
也是很有必要的。
一些參考: