Как мы уже говорили, скорее всего, вы теряете область действия this
.который вы можете увидеть, если вы console.log(this)
.Вот код, который должен работать.Изменение function
на лямбда-выражение не приведет к сбросу 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")
})
};