天天看点

使用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

的例子:

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

,实现下面的效果:

使用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-thunkconst 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 } = 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

    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 } = 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道面试题,并对每个问题作出了回答和解析。

使用useReducer + useContext 代替 react-redux

有需要的小伙伴,可以点击文末卡片领取这份文档,无偿分享

部分文档展示:

使用useReducer + useContext 代替 react-redux
使用useReducer + useContext 代替 react-redux
使用useReducer + useContext 代替 react-redux
使用useReducer + useContext 代替 react-redux

文章篇幅有限,后面的内容就不一一展示了

有需要的小伙伴,可以点下方卡片免费领取