正如标题所述,即使我已经定义了函数,我也无法弄清楚为什么我的函数authHandler无法读取未定义的属性“控件”。或者更确切地说,我认为我做到了-见下文。
请多多关注这个问题!
class SignUp extends Component {
state = {
controls: {
email: {
value: "",
valid: false,
validationRules: {
isEmail: true
},
touched: false
},
password: {
value: "",
valid: false,
validationRules: {
minLength: 6
},
touched: false
}
};
authHandler = () => {
return new Promise (function(resolve, reject) {
const authData = {
email: this.state.controls.email.value,
password: this.state.controls.password.value
};
this.props.onTryAuth(authData, this.state.authMode);
})
.then(() => {
this.props.onAddUserData(
this.state.controls.userName.value,
)
})
.catch(err => {
console.log(err);
alert("Oops! Something went wrong, please try again")
})
};
答案 0 :(得分:1)
如我们所建议,您可能正在失去this
范围。您可以查看自己是否console.log(this)
。这是应该起作用的代码。将function
更改为lambda表达式不会重置this
。另外,您发布的代码缺少两个}
。
class SignUp extends Component {
state = {
controls: {
email: {
value: "",
valid: false,
validationRules: {
isEmail: true
},
touched: false
},
password: {
value: "",
valid: false,
validationRules: {
minLength: 6
},
touched: false
}
}
}
};
authHandler = () => {
return new Promise ((resolve, reject) => {
const authData = {
email: this.state.controls.email.value,
password: this.state.controls.password.value
};
this.props.onTryAuth(authData, this.state.authMode);
})
.then(() => {
this.props.onAddUserData(
this.state.controls.userName.value,
)
})
.catch(err => {
console.log(err);
alert("Oops! Something went wrong, please try again")
})
};
或者您可以这样做
authHandler = () => {
// Obtain a reference to this when you enter this function
var self = this;
return new Promise (function (resolve, reject) {
// Because a function is declared above, this is reset to be
// that of the function scope, not the one entering authHandler.
const authData = {
email: self.state.controls.email.value,
password: self.state.controls.password.value
};
self.props.onTryAuth(authData, self.state.authMode);
})
.then(() => {
self.props.onAddUserData(
self.state.controls.userName.value,
)
})
.catch(err => {
console.log(err);
alert("Oops! Something went wrong, please try again")
})
};