使用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的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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:

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

useReducer 接受两个参数:第一个是上面我们介绍的reducer,第二个参数是初始化的state,返回的是个数组,数组第一项是当前最新的state,第二项是dispatch函数,它主要是用来dispatch不同的Action,从而触发reducer计算得到对应的state.

利用上面创建的reducer,看下如何使用useReducer这个Hook:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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的状态。

1
2
3
<Provider store={store}>
<App />
</Provider>

如果想要useReducer到达类似效果,我们需要用到useContext这个Hook。

2. useContext

useContext顾名思义,它是以Hook的方式使用React Context。先简单介绍 Context
Context设计目的是为了共享那些对于一个组件树而言是“全局”的数据,它提供了一种在组件之间共享值的方式,而不用显式地通过组件树逐层的传递props

1
const value = useContext(MyContext);

useContext:接收一个context对象(React.createContext 的返回值)并返回该context的当前值,当前的 context值由上层组件中距离当前组件最近的<MyContext.Provider>value prop 决定。来看官方给的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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,实现下面的效果:
picpic

react-redux实现

这里假设你已经熟悉了react-redux的使用,如果对它不了解可以去 查看.使用它来实现上面的需求:

  • 首先项目中导入我们所需类库后,创建Store

    Store/index.tsx

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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;
  • 创建reduceractionCreator

    reducer.tsx

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    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

1
2
3
const todoList = useSelector((state: RootState) => state.newTodo.todoList)
const dispatch = useDispatch()
......
useReducer + useContext 实现

为了实现修改颜色与字号的需求,在最开始的useReducer我们再添加两种action类型,完成后的reducer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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); 获取传递的颜色与字号,并进行样式绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 引入创建的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 也是很有必要的。

一些参考:

React

React Redux

用useState还是用useReducer