gpt4 book ai didi

javascript - Redux 形式奇怪的箭头函数语法

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:59 26 4
gpt4 key购买 nike

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

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

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

函数handleSubmit(values) { ... }

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

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

但这让我的 JSlint 变得疯狂(错误解析错误:意外的 token =)。我尝试了多种方法来重写它,包括使用编译后的 JS,但是当我这样做时,我收到错误,因为无法访问 props。

有人可以向我解释一下发生了什么事吗?

这是我使用编译后的 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

最佳答案

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

 <ContactForm onSubmit={this.handleSubmit} />

所以,如果您使用符号

function handleSubmit(values) { ... }

您仅传递函数定义,该函数定义将从 ContactForm 组件内部调用。发生这种情况时,“this”关键字的范围不会限定在您声明 ContactForm 的组件(本例中为 ContactPage)上,因此您将无权访问这些属性。

使用箭头符号

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

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

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

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

关于javascript - Redux 形式奇怪的箭头函数语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42782242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com