一. 概述
在 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 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,會被認為是只讀的 */}
<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
的使用,如果對它不了解可以去 查看.使用它來實現上面的需求:
-
首先項目中導入我們所需類庫后,創建
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;
-
創建
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('存在這個了值了') 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); }) } }
最后我們在組件中通過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.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);
獲取傳遞的顏色與字號,并進行樣式綁定
// 引入創建的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
,通過Context
把state
數據給組件樹中的所有組件使用 ,而不用通過props
添加回調函數的方式一層層傳遞,達到了數據共享的目的。
四. 總結
總體來說,相比react-redux
而言,使用useReducer
+ userContext
進行狀態管理更加簡單,免去了導入各種狀態管理庫以及中間鍵的麻煩,也不需要再創建store
和actionCreator
,對于新手來說,減輕了狀態管理的難度。對于一些小型項目完全可以用它來代替react-redux
,當然一些大型項目普遍還是使用react-redux
來進行的狀態管理,所以深入學習Redux
也是很有必要的。
一些參考: