【问题标题】:What is this chained ES6 arrow function?这个链接的 ES6 箭头函数是什么?
【发布时间】:2018-05-14 11:24:55
【问题描述】:

我正在使用 React、Redux 创建一个应用程序。

其中,我正在做一个 Redux 中间件,

有一部分看不懂。

代码如下:

const loggerMiddleware = store => next => action => {

    console.log('currentState', store.getState());

    console.log('action', action);

    const result = next(action);

    console.log(', store.getState());
    console.log('\n'); 

    return result;
}

export default loggerMiddleware; 

这个箭头函数=> => =>是什么? 箭头函数继续下去是没有意义的。

这是什么意思?

【问题讨论】:

  • 具有单个表达式的箭头函数会自动返回该值。 const x = foo => foo + "bar"。所以这在调用时返回一个字符串。但现在让x 返回一个返回字符串的函数const x = foo => foo2 => foo + foo2 + "bar"
  • 如果你在返回的函数周围加上括号可能会更清楚。 const x = foo => (foo2 => foo + foo2 + "bar")

标签: javascript function ecmascript-6 redux arrow-functions


【解决方案1】:

以下代码:

const loggerMiddleware = store => next => action => { 
    var result = /* .. */
    return result;
}

相当于:

const loggerMiddleware =  function(store) { 
    return function(next) {
        return function(action) {
            return result;
        }
    }
}

【讨论】:

  • 我还要补充一点,这允许将函数链接在一起。一个简单的例子是add => x => y => x+y,所以当你调用它时,你可以调用add(3)(5)并以8结束。与采用两个参数的函数相比,优势在于您可以传递它,例如,[20, 35, 42].map(add(5))x => x + 5 更易于阅读和维护。特别是因为你可以重复使用它,例如,如果你有shippingTax = add(5),那就更容易了。她的主题是“currying”,这就是它的基础 - 具有接受一个参数并返回另一个函数的函数
【解决方案2】:

这是一种技术(称为柯里化),它用多个函数替换接受一些参数的单个函数,每个函数接受这些参数的一部分,例如:

    const f1 = (x, b) => x + b;
    const f2 = x => b => x + b;
    
    const f1Result = f1(1, 2);
    // we can construct f2's result in multiple steps if we want because it returns a function, this can be helpful.
    let f2Result = f2(1);
    f2Result = f2Result(2);

    console.log('f1Result', f1Result);
    console.log('f2Result', f2Result);

您还可以阅读this 以更深入地了解此决定背后的理由,主要是:

有时我们想将一些本地状态与 store 和 next 相关联

【讨论】:

  • 我实际上是在另一条评论中写到的 :) 无论如何,为了让这个例子更具体,想象一下如果 f2 被称为 add 而不是 let f2result = f2(1) 你将变量命名为 addShippingTax = add(1)。这不那么抽象,直接说明了为什么你可能想要这个。例如,如果运费税发生变化,您只需对其进行修改。您还可以派生许多其他函数 addHandlingTaxincludeOverseasChargeshiddenFeeForDeveloperCoffee 等 - 当您使用已经有x=>y=>x+y
【解决方案3】:

Javascript 箭头函数是 8 个字符的 'function' 关键字的替换。使用箭头函数时,不需要在函数中写 return。

根据 Javascript 最佳实践,在您进行服务调用时尝试使用。用作函数关键字的简写。

有关更多信息,请参阅此链接上的一个很好的示例https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

【讨论】:

    猜你喜欢
    • 2022-11-27
    • 2016-01-25
    • 2022-01-14
    • 2016-12-09
    相关资源
    最近更新 更多