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

一、概念

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

二、简单例子

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

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 都是高阶组件,它们都接收一个组件作为参数,并返回一个新的组件。以下是伪代码 理解其意思即可

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 的所有特性。

你可能感兴趣的:(react,javascript,前端,react.js)