Redux 表单奇怪的箭头函数语法

Redux form weird arrow function syntax

所以我正在关注 getting started guide for Redux Form 并且我偶然发现了这个:

handleSubmit = (values) => { ... }

直觉上我认为它可以编译成这样简单的东西:

function handleSubmit(values) { ... }

但事实并非如此。实际上它编译成这样:

handleSubmit = function handleSubmit(values) { ... };

不过,这让我的 JSlint 变得疯狂 (error Parsing error: Unexpected token =)。而且我已经尝试了多种方法来重写它,包括改用编译后的 JS,但是当我这样做时,我得到了一个错误,因为无法访问道具。

谁能给我解释一下这是怎么回事?

这是我使用编译后的 JS 时的堆栈跟踪:

Uncaught TypeError: Cannot read property 'props' of undefined
    at handleSubmit (create.js:17)
    at doSubmit (handleSubmit.js:42)
    at handleSubmit.js:107
    at handleSubmit (handleSubmit.js:110)
    at Form.submit (reduxForm.js:540)
    at Object.ReactErrorUtils.invokeGuardedCallback (ReactErrorUtils.js:70)
    at executeDispatch (EventPluginUtils.js:85)
    at Object.executeDispatchesInOrder (EventPluginUtils.js:108)
    at executeDispatchesAndRelease (EventPluginHub.js:43)
    at executeDispatchesAndReleaseTopLevel (EventPluginHub.js:54)

这是我的 Eslint 配置的要点:

https://gist.github.com/webconsult/62bfa93054f261d92c186d39635f743c

我在 link 中看到 handleSubmit 函数是这样传递的:

 <ContactForm onSubmit={this.handleSubmit} />

因此,如果您使用符号

function handleSubmit(values) { ... }

您只传递函数定义,它将从 ContactForm 组件内部调用。发生这种情况时,'this' 关键字将不会作用于您声明 ContactForm 的组件(本例中为 ContactPage),因此您将无法访问道具。

使用箭头表示法

handleSubmit = (values) => { ... }

解决了这个问题,因为您没有传递函数定义,而是它的一个实例,因为这会创建一个带有实例化函数的 class 属性。由于箭头函数保持 'this' 关键字的范围,当 handleSubmit 被调用时, 'this' 将被正确地限定范围并且您将可以访问您定义回调的组件的道具。

请注意,将处理程序声明为 class 方法而不是 属性 并在将其传递给 ContactForm 时将范围绑定到它可以实现相同的效果:

class ContactPage extends React.Component {
  handleSubmit(values) {
    // Do something with the form values
    console.log(values);
  }
  render() {
    return (
      <ContactForm onSubmit={this.handleSubmit.bind(this)} />
    );
  }
}