6成都网站建设,成都网站建设需多少钱,上饶有哪些做网站的店,怎么一键打开两个wordpress一、概念
compose 是 Redux 提供的一个辅助函数#xff0c;它的作用是将多个函数组合成一个新的函数#xff0c;使这些函数能够按照从右到左的顺序依次执行。
二、简单例子
我们先使用 compose 函数将三个函数 f、g 和 h 组合成一个新的函数 composedFunc。在组合后的函数…一、概念
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 的所有特性。