【问题标题】:Why is this function in the redux-form source code wrapped by another function?为什么redux-form源代码中的这个函数被另一个函数包裹了?
【发布时间】:2018-05-31 09:04:07
【问题描述】:

我的问题与redux-form 源代码中的实现细节有关。简单地说,我想深入了解一下后面的推理和想法,这些代码可以在 src/createField.js herehere 中找到。

this.context._reduxForm.register(
     newName,
     'Field',
     () => nextProps.validate,
     () => nextProps.warn
)

我的问题不是关于这些函数的使用方式或位置,而是为什么这些函数以它们的方式包装。例如为什么不简单地使用:

this.context._reduxForm.register(
  newName,
  'Field',
  nextProps.validate,
  nextProps.warn
)

我的猜测是它与在父组件中存储对这些函数的直接引用有关。我对此的兴趣与我在 SO 上问过的另一个 question 有关。

【问题讨论】:

    标签: javascript reactjs redux redux-form


    【解决方案1】:

    this 的值取决于函数的调用方式。将函数调用与对象分离将断开与 this 中该对象的连接。

    var nextProps = {
        validate: function () { console.log("This is ", this); }
    };
    
    function callFunction(callback) {
        callback();
    }
    
    console.log("======");
    console.log("Preserve this");
    callFunction(() => nextProps.validate());
    console.log("======");
    console.log("Don't preserve this");
    callFunction(nextProps.validate);

    【讨论】:

    • 有趣的观察 - 也许我并不完全相信你的例子:函数是这样包装的 () => nextProps.validate 而不是 () => nextProps.validate() 所以当值是 unwrapped 最后是 usedthis 的范围没有保留。还是我错过了什么?
    • 请注意,validate 可以是一个函数或函数数组,如果没有传入任何值,则为 undefined。
    • @StuartBourhill —() => nextProps.validate 创建了一个提及 nextProps.validate 但没有调用它并且实际上什么都不做的函数。
    猜你喜欢
    • 1970-01-01
    • 2017-12-28
    • 2021-06-24
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    相关资源
    最近更新 更多