【问题标题】:Difference between plain function and function returning multiple functions普通函数和返回多个函数的函数之间的区别
【发布时间】:2018-01-20 21:43:38
【问题描述】:

我不明白下面两个语句之间的区别。为什么在记录器中返回一个函数两次会使其有所不同?

返回函数

const logger = store => next => action => {
    let result
    console.groupCollapsed("dispatching", action.type)
    console.log('prev state', store.getState())
    console.log('action', action)
    result = next(action)
    console.log('next state', store.getState())
    console.groupEnd()
    return result
}

不返回函数

const logger = (store, next, action) => {
    let result
    console.groupCollapsed("dispatching", action.type)
    console.log('prev state', store.getState())
    console.log('action', action)
    result = next(action)
    console.log('next state', store.getState())
    console.groupEnd()
    return result
}

【问题讨论】:

  • 好吧,这都是关于闭包的,然后您可以传递一个在第一种情况下已经知道storenext 函数的函数,并且只有action 是可变的。在第二个函数中,没有一个参数是固定的,可以进行较少的优化。

标签: javascript reactjs redux middleware


【解决方案1】:

这样您就可以对函数部分应用参数。例如,您可能只知道(或在范围内)您在特定时间点的 storenext 函数。稍后,在执行期间,您可能会拥有 action 参数,但 store 超出范围。

因此,您部分应用前两个参数,然后传递返回的函数,以便最终可以在稍后阶段使用第三个参数执行它。当它最终使用第三个参数执行时,它可以访问前两个参数,因为它们包含在部分应用的函数中。一个例子可能会澄清:

 const store = {
    getState: () => 'foo'
}
// this can be passed around, it creates a closure around store so will have access to it later
const partialLogger = logger(store)((ac) => ({
    ac,
    bar: 2
}));
// some time later - execute
const res = partialLogger({ type: 'baz' });
console.log('>res', res);

【讨论】:

  • 太棒了!我了解 logger 函数的闭包方面,但这有助于连接点。
猜你喜欢
  • 2021-08-21
  • 2019-07-06
  • 2020-03-28
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多