在学习compose函数以前,咱们先来回忆一下reduce函数编程
arr.reduce(callback[, initialValue])
复制代码
callback有四个参数,分别是:redux
var a = []
a.reduce(function(acc, curr, i){
return acc + curr
},10)
// 10
复制代码
注意:若是是空数组调用reduce函数会报错: Uncaught TypeError: Reduce of empty array with no initial value。 可是若是给accumulator一个初始值,做为reduce的第二个参数,这样空数组也就不会报错啦。 api
redux中的 compose是 redux暴露出来的一个惟一能够单独使用的api ,由于它其实和redux自己没有很大的关系,而是函数式编程的组合函数(也就是数学中的复合函数)。数组
它大概长这个样子bash
//将几个函数拼凑在一块儿,产生一个新的函数
var a = compose(f1, f2, f3)(x)
//其实执行的是[f1,f2,f3].reduce((a, b) => (...args) => a(b(...args)))
//从右到左依次执行括号中的函数,第一个执行完的结果做为第二个函数执行时的参数,而后迭代下去。
复制代码
在redux中是这样实现compose的函数式编程
//在redux中的compose函数,它使用了reduce方法。
export default function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
}
if (funcs.length === 1) {
return funcs[0]
}
return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
复制代码
到如今为止,已经大概知道compose是怎么工做的了,那就看一下在项目中遇到的compose函数
const Header = compose(
withTranslation('nav', 'branding'), //是一个国际化的东东(i18n)
connect(state => ({
user: state.profile.user || {},
pathname: state.router.location?.pathname || '',
expireTime: state.profile.license?.not_valid_after || 0,
})),
)(
class Header extends PureComponent {
render() {
const { user, t, expireTime, pathname } = this.props
return (
<StyledHeader>
xxx
</StyledHeader>
)
}
},
)
export default Header
复制代码
emmm....理解的比较浅,但愿大佬们能够多加指点🙏学习
不要吹灭你的灵感和你的想象力; 不要成为你的模型的奴隶。 ——文森特・梵高ui