[英]Cannot read property 'controls' of undefined when using function()
正如標題所指出的,即使我已經定義了我的函數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")
})
};
正如我們建議的那樣,您很可能正在失去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")
})
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.