Context与Reducer
Context与Reducer
Context是React提供的一种跨组件的通信方案,useContext与useReducer是在React 16.8之后提供的Hooks API,我们可以通过useContext与useReducer来完成全局状态管理例如Redux的轻量级替代方案。
useContext
React Context适用于父子组件以及隔代组件通信,React Context提供了一个无需为每层组件手动添加props就能在组件树间进行数据传递的方法。一般情况下在React应用中数据是通过props属性自上而下即由父及子进行传递的,而一旦需要传递的层次过多,那么便会特别麻烦,例如主题配置theme、地区配置locale等等。Context提供了一种在组件之间共享此类值的方式,而不必显式地通过组件树的逐层传递props。例如React-Router就是使用这种方式传递数据,这也解释了为什么<Router>要在所有<Route>的外面。
当然在这里我们还是要额外讨论下是不是需要使用Context,使用Context可能会带来一些性能问题,因为当Context数据更新时,会导致所有消费Context的组件以及子组件树中的所有组件都发生re-render。那么,如果我们需要类似于多层嵌套的结构,应该去如何处理,一种方法是我们直接在当前组件使用已经准备好的props渲染好组件,再直接将组件传递下去。
export const Page: React.FC<{
user: { name: string; avatar: string };
}> = props => {
const user = props.user;
const Header = (
<>
<span>
<img src={user.avatar}></img>
<span>{user.name}</span>
</span>
<span>...</span>
</>
);
const Body = <></>;
const Footer = <></>;
return (
<>
<Component header={Header} body={Body} footer={Footer}></Component>
</>
);
};
这种对组件的控制反转减少了在应用中要传递的props数量,这在很多场景下可以使得代码更加干净,使得根组件可以有更多的把控。但是这并不适用于每一个场景,这种将逻辑提升到组件树的更高层次来处理,会使得这些高层组件变得更复杂,并且会强行将低层组件适应这样的形式,这可能不会是你想要的。这样的话,就需要考虑使用Context了。
说回Context,Context提供了类似于服务提供者与消费者模型,在通过React.createContext创建Context后,可以通过Context.Provider来提供数据,最后通过Context.Consumer来消费数据。在React 16.8之后,React提供了useContext来消费Context,useContext接收一个Context对象并返回该Context的当前值。
// https://codesandbox.io/s/react-context-reucer-q1ujix?file=/src/store/context.tsx
import React, { createContext } from "react";
export interface ContextProps {
state: {
count: number;
};
}
const defaultContext: ContextProps = {
state: {
count: 1
}
};
export const AppContext = createContext<ContextProps>(defaultContext);
export const AppProvider: React.FC = (props) => {
const { children } = props;
return (
<AppContext.Provider value={defaultContext}>{children}</AppContext.Provider>
);
};
// https://codesandbox.io/s/react-context-reucer-q1ujix?file=/src/App.tsx
import React, { useContext } from "react";
import { AppContext, AppProvider } from "./store/context";
interface Props {}
const Children: React.FC = () => {
const context = useContext(AppContext);
return <div>{context.state.count}</div>;
};
const App: React.FC<Props> = () => {
return (
<AppProvider>
<Children />
</AppProvider>
);
};
export default App;
useReducer
useReducer是useState的替代方案,类似于Redux的使用方法,其接收一个形如(state, action) => newState的reducer,并返回当前的state以及与其配套的dispatch方法。
const initialState = { count: 0 };
type State = typeof initialState;
const ACTION = {
INCREMENT: "INCREMENT" as const,
SET: "SET" as const,
};
type IncrementAction = {
type: typeof ACTION.INCREMENT;
};
type SetAction = {
type: typeof ACTION.SET;
payload: number;
};
type Action = IncrementAction | SetAction;
function reducer(state: State, action: Action) {
switch (action.type) {
case ACTION.INCREMENT:
return { count: state.count + 1 };
case ACTION.SET:
return { count: action.payload };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<div>
<button onClick={() => dispatch({ type: ACTION.INCREMENT })}>INCREMENT</button>
<button onClick={() => dispatch({ type: ACTION.SET, payload: 10 })}>SET 10</button>
</div>
</>
);
}
或者我们也可以相对简单地去使用useReducer,例如实现一个useForceUpdate,当然使用useState实现也是可以的。
function useForceUpdate() {
const [, forceUpdateByUseReducer] = useReducer<(x: number) => number>(x => x + 1, 0);
const [, forceUpdateByUseState] = useState<Record<string, unknown>>({});
return { forceUpdateByUseReducer, forceUpdateByUseState: () => forceUpdateByUseState({}) };
}
useContext + useReducer
对于状态管理工具而言,我们需要的最基础的就是状态获取与状态更新,并且能够在状态更新的时候更新视图,那么useContext与useReducer的组合则完全可以实现这个功能,也就是说,我们可以使用useContext与useReducer来实现一个轻量级的redux。
// https://codesandbox.io/s/react-context-reducer-q1ujix?file=/src/store/reducer.ts
export const initialState = { count: 0 };
type State = typeof initialState;
export const ACTION = {
INCREMENT: "INCREMENT" as const,
SET: "SET" as const
};
type IncrementAction = {
type: typeof ACTION.INCREMENT;
};
type SetAction = {
type: typeof ACTION.SET;
payload: number;
};
export type Action = IncrementAction | SetAction;
export const reducer = (state: State, action: Action) => {
switch (action.type) {
case ACTION.INCREMENT:
return { count: state.count + 1 };
case ACTION.SET:
return { count: action.payload };
default:
throw new Error();
}
};
// https://codesandbox.io/s/react-context-reducer-q1ujix?file=/src/store/context.tsx
import React, { createContext, Dispatch, useReducer } from "react";
import { reducer, initialState, Action } from "./reducer";
export interface ContextProps {
state: {
count: number;
};
dispatch: Dispatch<Action>;
}
const defaultContext: ContextProps = {
state: {
count: 1
},
dispatch: () => void 0
};
export const AppContext = createContext<ContextProps>(defaultContext);
export const AppProvider: React.FC = (props) => {
const { children } = props;
const [state, dispatch] = useReducer(reducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
};
// https://codesandbox.io/s/react-context-reducer-q1ujix?file=/src/App.tsx
import React, { useContext } from "react";
import { AppContext, AppProvider } from "./store/context";
import { ACTION } from "./store/reducer";
interface Props {}
const Children: React.FC = () => {
const { state, dispatch } = useContext(AppContext);
return (
<>
Count: {state.count}
<div>
<button onClick={() => dispatch({ type: ACTION.INCREMENT })}>
INCREMENT
</button>
<button onClick={() => dispatch({ type: ACTION.SET, payload: 10 })}>
SET 10
</button>
</div>
</>
);
};
const App: React.FC<Props> = () => {
return (
<AppProvider>
<Children />
</AppProvider>
);
};
export default App;
我们直接使用Context与Reducer来完成状态管理是具有一定优势的,例如这种实现方式比较轻量,且不需要引入第三方库等。当然,也有一定的问题需要去解决,当数据变更时,所有消费Context的组件都会需要去渲染,当然React本身就是以多次的re-render来完成的Virtual DOM比较由此进行视图更新,在不出现性能问题的情况下这个优化空间并不是很明显,对于这个问题我们也有一定的优化策略:
- 可以完成或者直接使用类似于
useContextSelector代替useContext来尽量避免不必要的re-render,这方面在Redux中使用还是比较多的。 - 可以使用
React.memo或者useMemo的方案来避免不必要的re-render,通过配合useImmerReducer也可以在一定程度上缓解re-render问题。 - 对于不同上下文背景的
Context进行拆分,用来做到组件按需选用订阅自己的Context。此外除了层级式按使用场景拆分Context,一个最佳实践是将多变的和不变的Context分开,让不变的Context在外层,多变的Context在内层。
此外,虽然我们可以直接使用Context与Reducer来完成基本的状态管理,我们依然也有着必须使用redux的理由:
redux拥有useSelector这个Hooks来精确定位组件中的状态变量,来实现按需更新。redux拥有独立的redux-devtools工具来进行状态的调试,拥有可视化的状态跟踪、时间回溯等功能。redux拥有丰富的中间件,例如使用redux-thunk来进行异步操作,redux-toolkit官方的工具集等。
每日一题
https://github.com/WindrunnerMax/EveryDay
参考
https://zhuanlan.zhihu.com/p/360242077
https://zhuanlan.zhihu.com/p/313983390
https://www.zhihu.com/question/24972880
https://www.zhihu.com/question/335901795
https://juejin.cn/post/6948333466668777502
https://juejin.cn/post/6973977847547297800
https://segmentfault.com/a/1190000042391689
https://segmentfault.com/a/1190000023747431
https://zh-hans.reactjs.org/docs/context.html#gatsby-focus-wrapper
https://stackoverflow.com/questions/67537701/react-topic-context-vs-redux
Context与Reducer的更多相关文章
- MapReduce的ReduceTask任务的运行源码级分析
MapReduce的MapTask任务的运行源码级分析 这篇文章好不容易恢复了...谢天谢地...这篇文章讲了MapTask的执行流程.咱们这一节讲解ReduceTask的执行流程.ReduceTas ...
- hadoop2 作业执行过程之reduce过程
reduce阶段就是处理map的输出数据,大部分过程和map差不多 //ReduceTask.run方法开始和MapTask类似,包括initialize()初始化,根据情况看是否调用runJobCl ...
- 【Hadoop代码笔记】Hadoop作业提交之Child启动reduce任务
一.概要描述 在上篇博文描述了TaskTracker启动一个独立的java进程来执行Map任务.接上上篇文章,TaskRunner线程执行中,会构造一个java –D** Child address ...
- MapReduce编程系列 — 4:排序
1.项目名称: 2.程序代码: package com.sort; import java.io.IOException; import org.apache.hadoop.conf.Configur ...
- MapReduce编程系列 — 3:数据去重
1.项目名称: 2.程序代码: package com.dedup; import java.io.IOException; import org.apache.hadoop.conf.Configu ...
- MapReduce编程系列 — 2:计算平均分
1.项目名称: 2.程序代码: package com.averagescorecount; import java.io.IOException; import java.util.Iterator ...
- hadoop 各种counter 解读
http://blog.sina.com.cn/s/blog_61ef49250100uxwh.html 经过了两天的休息与放松,精神饱满了吧?上星期我们学习了MapReduce的过程,了解了其基本过 ...
- MapReduce UnitTest
通常情况下,我们需要用小数据集来单元测试我们写好的map函数和reduce函数.而一般我们可以使用Mockito框架来模拟OutputCollector对象(Hadoop版本号小于0.20.0)和Co ...
- 使用Hadoop的MapReduce与HDFS处理数据
hadoop是一个分布式的基础架构,利用分布式实现高效的计算与储存,最核心的设计在于HDFS与MapReduce,HDFS提供了大量数据的存储,mapReduce提供了大量数据计算的实现,通过Java ...
- underscore.js源码解析【集合】
// Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `f ...
随机推荐
- 结构体中ElementType的使用
1.问题 在定义结构体时,对于元素值,为什么喜欢使用ElementType而不是直接使用int或者char等等? 2.结论 对于int get_result(int x); 和 int get_res ...
- [转帖]Java程序在K8S容器部署CPU和Memory资源限制相关设置
2019-04-297279 版权 本文涉及的产品 容器服务 Serverless 版 ACK Serverless,317元额度 多规格 推荐场景: 立即试用 容器镜像服务 ACR,镜像仓库100个 ...
- 【转帖】Linux中如何取消ln链接?(linuxln取消)
https://www.dbs724.com/163754.html Linux系统使用ln命令可以快速创建链接,ln链接是指把文件和目录链接起来,当改变源时可以快速地改变整个目录下的文件和目录.有时 ...
- [转帖]英伟达H100市面价格飙升!Elon Musk:每个人都在买GPU
https://cj.sina.com.cn/articles/view/5115326071/130e5ae7702001w8oz?sudaref=www.baidu.com&display ...
- [转帖]linux删除文本文件空白行
linux删除文本文件空白行https://www.zhihu.com/people/chen-kai-84-54-75 sed命令 在Linux中,可以使用sed命令批量删除文本中的空白行.以下是一 ...
- 【转帖】在ECS上配置skywalking-nginx-lua
https://help.aliyun.com/document_detail/197660.html 此处以在CentOS 7.0上的操作为例. 配置Lua运行环境. 安装工具库. yum in ...
- [转帖]解析Linux gcore: 揭示程序内存捕获的秘密(linuxgcore)
https://www.dbs724.com/133618.html Linux gcore 是一种在Linux系统中使用命令行工具捕获进程内存内容的方法.它允许程序员制定程序的一个内存快照,从而帮助 ...
- Docker 安装Oracle12c的镜像修改字符集 并且进行启动的简单过程
学习来自 昨天晚上转帖的文章 这里面添加一些自己的内容 首先获取配置文件 git clone https://github.com/oracle/docker-images.git 获取之后比较容易了 ...
- 阿里云ECS虚拟机磁盘扩容过程
阿里云ECS虚拟机磁盘扩容过程 背景 公司同事将很早之前的一个虚拟机重新开机. 就好将一套demo环境安装进这个ECS虚拟机里面 这个机器系统盘只有40G的空间. 导致磁盘空间不足. 其实一开始我不知 ...
- MySQL数据库存储varchar时多大长度会出现行迁移?
最近客户现场有人问过mysql数据库的一些参数配置的问题, 这边数据库需要将strict 严格模式关掉, 目的是为了保证数据库在插入字段时不会出现8126的长度限制错误问题. 但是一直很困惑, mys ...