Javascript 我在react js中使用firebase注册三次时遇到了一个问题
我是新手,我正在使用firebase进行身份验证。。希望有人能帮我解决这个问题,为什么我的注册组件调用了三次。 这是我的注册组件Javascript 我在react js中使用firebase注册三次时遇到了一个问题,javascript,reactjs,firebase,google-cloud-firestore,firebase-authentication,Javascript,Reactjs,Firebase,Google Cloud Firestore,Firebase Authentication,我是新手,我正在使用firebase进行身份验证。。希望有人能帮我解决这个问题,为什么我的注册组件调用了三次。 这是我的注册组件 this.state = { displayName: "", email: "", password: "", confirmPassword: "", }; //this is a form submit metho
this.state = {
displayName: "",
email: "",
password: "",
confirmPassword: "",
};
//this is a form submit method
handleSubmit = async (event) => {
event.preventDefault();
const { displayName, email, password, confirmPassword } = this.state;
if (password !== confirmPassword) {
alert("passwords don't match");
return;
}
try {
const { user } = await auth.createUserWithEmailAndPassword(
email,
password
);
await createUserProfileDocument(user, { displayName });
this.setState({
displayName: "",
email: "",
password: "",
confirmPassword: "",
});
} catch (error) {
console.error(error);
}
};
这是我的app.js函数
unsubscribeFromAuth = null;
componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
userRef.onSnapshot((snapshot) => {
this.setState(
{
currentUser: {
id: snapshot.id,
...snapshot.data(),
},
}
);
console.log(this.state.currentUser);
});
} else {
this.setState({ currentUser: userAuth });
}
});
}
App.js:33
{id: "U43Vz2cgEETiWNMoPsXhXDU82Hz1", displayName: "hgh", email: "tmh3000@yahoo.com", createdAt: t}
App.js:33
{id: "U43Vz2cgEETiWNMoPsXhXDU82Hz1", displayName: null, createdAt: t, email: "tmh3000@yahoo.com"}
App.js:33
{id: "U43Vz2cgEETiWNMoPsXhXDU82Hz1", createdAt: t, email: "tmh3000@yahoo.com", displayName: "hgh"}
控制台输出当我单击“注册”按钮时它为什么会呼叫三次
unsubscribeFromAuth = null;
componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
userRef.onSnapshot((snapshot) => {
this.setState(
{
currentUser: {
id: snapshot.id,
...snapshot.data(),
},
}
);
console.log(this.state.currentUser);
});
} else {
this.setState({ currentUser: userAuth });
}
});
}
App.js:33
{id: "U43Vz2cgEETiWNMoPsXhXDU82Hz1", displayName: "hgh", email: "tmh3000@yahoo.com", createdAt: t}
App.js:33
{id: "U43Vz2cgEETiWNMoPsXhXDU82Hz1", displayName: null, createdAt: t, email: "tmh3000@yahoo.com"}
App.js:33
{id: "U43Vz2cgEETiWNMoPsXhXDU82Hz1", createdAt: t, email: "tmh3000@yahoo.com", displayName: "hgh"}
我认为这是因为当前用户的状态改变了三次 请先查看属性值,它是“hgh”,然后是“null”,再次查看“hgh”
根据react,当状态更改时组件重新呈现可以调用三次吗?如果不行,我该怎么做才能停止调用三次呢?由于firebase的auth库,您没有做错什么。