Я новичок в firebase и сумел успешно настроить аутентификацию по электронной почте/паролю на основе того, что мне удалось собрать из документации/примеров в Интернете. Однако я столкнулся с каким-то странным поведением. Прежде всего здесь мой firebase код аутентификации, который находится в функции Реагировать компонента:Firebase - проблема с Auth во время регистрации
class SignupComponentInner extends Component {
toggleSignupLayoverAction(event){
this.props.toggleSignupLayover("false")
}
signUp(e) {
e.preventDefault();
var firstName = $('.signup-first-name').val();
var lastName = $('.signup-last-name').val();
var userName = $('.signup-user-name').val();
var password = $('.signup-user-password').val();
var email = $('.signup-email').val();
var auth = firebase.auth();
const promise = auth.createUserWithEmailAndPassword(email,password).then(function(user) {
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: userName,
}).then(function() {
// Update successful.
// new db code here
firebase.database().ref('users/' + user.uid).set({
firstName: firstName,
lastName: lastName,
userName: userName
})
// end new db code here
}, function(error) {
// An error happened.
});
}, function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
console.error(error);
}
// [END_EXCLUDE]
});
promise.catch(e => console.log(e.message));
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser) {
console.log("logged in");
var sendUserId = firebaseUser.uid;
this.props.logUserIn(sendUserId)
} else {
console.log("not logged in")
}
});
}
render() {
return (
<div onClick={this.toggleSignupLayoverAction.bind(this)} className="signup-cont-par">
<div className="signup-component-inner">
<div className="signup-component-content" onClick={cancelBubble.bind(this)}>
<h2>Sign up today!</h2>
<form className="signup-form-elem">
<input placeholder="First Name" className="signup-first-name" type="text"></input>
<input placeholder="Last Name" className="signup-last-name" type="text"></input>
<input placeholder="Username" className="signup-user-name" type="text"></input>
<input placeholder="Password" className="signup-user-password" type="password"></input>
<input placeholder="Email Address" className="signup-email" type="text"></input>
<button onClick={this.signUp.bind(this)}>Sign Up</button>
</form>
</div>
</div>
</div>
)
}
}
Так регистрация часть работает именно так, как должно, но его регистрационную часть здесь, которая вызывает вопросы:
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser) {
console.log("logged in");
var sendUserId = firebaseUser.uid;
this.props.logUserIn(sendUserId)
} else {
console.log("not logged in")
}
});
Это в основном выполняется дважды, как im, получая console.log «вошел в систему» дважды в регистре. Не знаете, почему это так?
Другая проблема - это функция, которую она вызывает из реквизита. this.props.logUserIn(sendUserId)
Эта функция в основном скрывает «создать учетную запись» CTA и заменяет ее приветствием {{username}}. Имя пользователя обновляется при регистрации, но очень странно оно будет обновляться до любого имени пользователя, которое я зарегистрировал в предыдущем регистре! Вот функция logUserIn, если это помогает:
logUserIn(userId) {
var db = firebase.database();
var ref = db.ref('/users/' + userId);
console.log(userId);
ref.once('value').then((snapshot) => {
var userObject = snapshot.val();
var loggedUserName = userObject.userName;
this.setState({
LoggedInUsername:loggedUserName
})
});
this.setState({
loggedInState:true,
LoggedInId:userId,
signingUp:"inactive"
})
},
Здесь loggedUserName
это состояние, которое передается вниз к главному компоненту, чтобы показать имя пользователя, который только что был зарегистрирован (тот, который неправильно с указанием предыдущего зарегистрированного лица при он должен показывать последние). Не знаю, где я ошибся.