Javascript 将this.props传递给嵌套函数
以下是我想做的:Javascript 将this.props传递给嵌套函数,javascript,reactjs,Javascript,Reactjs,以下是我想做的: handleFormSubmit(event){ let currentComponent = this; const { t } = this.props; event.preventDefault(); UserService.isAccount(event, this.props).then(function(status) { if(status === statusCode.OK
handleFormSubmit(event){
let currentComponent = this;
const { t } = this.props;
event.preventDefault();
UserService.isAccount(event, this.props).then(function(status) {
if(status === statusCode.OK) {
UserService.forgottenPasswordEmail(event, currentComponent.props).then(function (status){
toast.notify("t('forgottenPassword.emailSent')");
})
} else {
toast.notify(t('forgottenPassword.emailNotSent'));
}
})
}
如上所述,我试图将this.props传递给UserService.isAccount函数,传递给UserService.forgottenPasswordEmail函数,该函数在最后一个函数的.then中调用。我试图用currentComponent引用它,但它似乎不起作用,因为我得到“无法读取属性”构造函数为null
我怎样才能做到这一点
更新。这显示未处理的拒绝(TypeError):无法读取未定义的属性“target”
handleFormSubmit(event){
let currentComponent = this;
const { t } = this.props;
event.preventDefault();
const { aux } = event;
UserService.isAccount(aux, this.props).then(function(status) {
if(status === statusCode.OK) {
UserService.forgottenPasswordEmail(aux, currentComponent.props).then(function (status){
toast.notify("t('forgottenPassword.emailSent')");
})
} else {
toast.notify(t('forgottenPassword.emailNotSent'));
}
})
}
我相信这会完成你想要做的。一个问题是您正在丢失“this”的上下文,并且
让currentComponent=this代码>没有做我认为您认为它正在做的事情。您需要使用ref来代替。但看起来你甚至不需要这么做
handleFormSubmit(event){
const { props } = this;
const { t } = props;
event.preventDefault();
UserService.isAccount(event, props).then(function(status) {
if(status === statusCode.OK) {
UserService.forgottenPasswordEmail(event, props).then(function (status){
toast.notify("t('forgottenPassword.emailSent')");
})
} else {
toast.notify(t('forgottenPassword.emailNotSent'));
}
})
}
UserService.isAccount(event,this.props)
中的this
将引用UserService对象,而不是handleFormSubmit方法的父组件
您需要在变量中保存对这些props的引用,然后在调用UserService.isAccount,
时引用所述变量,我相信您已经在使用const{t}=this.props
因此,将方法调用更改为UserService.isAccount(event,t)
应该可以修复引用错误。对我有效的方法是添加event.persist()
我的函数isAccount和forgottenPasswordEmail设置为接收this.props,但不接收“this”,在本例中,您将其命名为props。如果它们彼此不嵌套,并且我只将event和this.props传递给它们,则两者都可以正常工作。props来自于:const{props}=this;或者只是使用箭头函数。@emilebergron是的-我应该说原因。更新以反映这一点。这是否回答了您的问题?我不认为问题出在这个
,甚至错误消息也没有说这个
是个问题。你不能异步传递React事件
对象,但是你可以捕获你需要的值并在异步回调中传递这些值。要了解更多关于上下文的信息:让currentComponent=this代码>没有做我认为您认为它正在做的事情。您需要使用ref来代替。虽然看起来你甚至不需要这么做。
handleFormSubmit(event){
let currentComponent = this;
const { t } = this.props;
event.preventDefault();
event.persist();
UserService.isAccount(event, this.props).then(function(status) {
if(status === statusCode.OK) {
UserService.forgottenPasswordEmail(event, currentComponent.props).then(function (status){
toast.notify(t('forgottenPassword.emailSent'));
})
} else {
toast.notify(t('forgottenPassword.emailNotSent'));
}
})
}