redux中compose的学习

204

在学习compose函数之前,我们先来回忆一下reduce函数

arr.reduce(callback[, initialValue])

callback有四个参数,分别是:

  • accumulator: 它是初始值,也是累加器返回的值
  • currentValue: 当前正在参与计算的元素
  • currentIndex(可选):当前currentValue的索引,如果recude没有第二个参数,currentIndex是从0开始,如果有第二个参数,那么就从1开始。
  • array(可选):调用reduce函数的数组
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的第二个参数,这样空数组也就不会报错啦。

redux中的 compose是 redux暴露出来的一个唯一可以单独使用的api ,因为它其实和redux本身没有很大的关系,而是函数式编程的组合函数(也就是数学中的复合函数)。

它大概长这个样子

//将几个函数拼凑在一起,产生一个新的函数
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....理解的比较浅,希望大佬们可以多加指点🙏

不要吹灭你的灵感和你的想象力; 不要成为你的模型的奴隶。 ——文森特・梵高