a=>b => c这种函数如何理解

es6中高阶函数多个箭头函数级联的情况如何很好的理解代码

const setTitle = (title) => (WrappedComponent) => {
   return class extends React.Component {
      componentDidMount() {
          document.title = title
      }
      render() {
         return <WrappedComponent {...this.props} />
      }
   }
}

PS追问一下:大家说的,我能够理解了,但是每次都要在头脑中做转换,感觉代码可读性也不是特别的好,也可能是我太菜了。还有这种写法是不是最多也就写两层。

阅读 3.9k
5 个回答

其实就是ES6的柯里化写法,也就是先定义一个函数,然后再其内再返回一个新的函数以接受第二个参数
补充:
可以不只是两层。

const setTitle = (title) => (WrappedComponent) => {}
//格式上可以看做
const setTitle = function(title){
    return function(WrappedComponent){
       
    }
}
const setTitle = (title) => {
return (WrappedComponent) => {
   return class extends React.Component {
      componentDidMount() {
          document.title = title
      }
      render() {
         return <WrappedComponent {...this.props} />
      }
   }
 }
}

从右往左,相当于(title) => {return ()=>{}}

新手上路,请多包涵
const a => b => c => { /* code */ }
// 等同于
const c = (a, b) => { /* code */ }

第一种写法可以当成是第二种的克里化

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题