第48节—— redux 中的 compose——了解

一、概念

compose 是 Redux 提供的一个辅助函数,它的作用是将多个函数组合成一个新的函数,使这些函数能够按照从右到左的顺序依次执行。

二、简单例子

我们先使用 compose 函数将三个函数 f、g 和 h 组合成一个新的函数 composedFunc。在组合后的函数中,输入值 5 将按照 h、g、f 的顺序依次执行,输出结果为 4

jsx 复制代码
import { compose } from 'redux';

const f = (x) => x + 1;
const g = (x) => x * 2;
const h = (x) => x - 3;

const composedFunc = compose(f, g, h);
console.log(composedFunc(5)); // 输出结果为 5

三、在react中的应用

当我们需要将多个高阶组件(HOC)组合起来时,就可以使用compose 函数。可以避免高阶组件嵌套的问题。

在这个例子中,withUser, withRouter, withStyle 都是高阶组件,它们都接收一个组件作为参数,并返回一个新的组件。以下是伪代码 理解其意思即可

jsx 复制代码
import { compose } from 'redux';
// 可以帮助我们在组件中访问样式
import { withStyle } from 'react-with-style';
// 可以帮助我们在组件中访问路由信息
import { withRouter } from 'react-router';
// 可以帮助我们在组件中访问用户的信息
import { withUser } from 'components/hoc/withUser';

const enhance = compose(
  withUser,
  withRouter,
  withStyle(styles)
);

const MyComponent = (props) => {
  // ...
};

export default enhance(MyComponent);

在上面的例子中,我们使用 compose 函数将 withUser, withRouter, withStyle 这三个高阶组件组合成了一个新的 HOC enhance,使用 enhance 函数后,MyComponent 组件就具备了 HOC withUser, withRouter, withStyle 的所有特性。

相关推荐
木斯佳41 分钟前
前端八股文面经大全:bilibili生态技术方向二面 (2026-03-25)·面经深度解析
前端·ai·ssd·sse·rag
不会写DN1 小时前
Gin 日志体系详解
前端·javascript·gin
冬夜戏雪1 小时前
实习面经记录(十)
java·前端·javascript
爱学习的程序媛3 小时前
【Web前端】JavaScript设计模式全解析
前端·javascript·设计模式·web
小码哥_常3 小时前
从SharedPreferences到DataStore:Android存储进化之路
前端
老黑3 小时前
开源工具 AIDA:给 AI 辅助开发加一个数据采集层,让 AI 从错误中自动学习(Glama 3A 认证)
前端·react.js·ai·nodejs·cursor·vibe coding·claude code
薛先生_0993 小时前
js学习语法第一天
开发语言·javascript·学习
jessecyj3 小时前
Spring boot整合quartz方法
java·前端·spring boot
苦瓜小生3 小时前
【前端】|【js手撕】经典高频面试题:手写实现function.call、apply、bind
java·前端·javascript
天若有情6733 小时前
前端HTML精讲03:页面性能优化+懒加载,搞定首屏加速
前端·性能优化·html