当我登录或注册时,一切都很正常。但如果我重新加载页面,我必须再次登录。有办法解决这个问题吗?我自己也试过建立毅力,但没有用。这是我的代码
const iniciarSesion = (e) => {
const auth = getAuth();
setPersistence(auth, browserLocalPersistence)
.then(() => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
setVentana("Tienda")
})
.catch((error) => {
console.log(error)
});
})
}
const registar = (e) => {
const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
setVentana("Tienda")
})
.catch((error) => {
console.error(error)
});
}
在大多数基于浏览器的环境中,Firebase已经持久化,并在重新加载页面时恢复用户凭据。来自Firebase关于身份验证持久性的文档:
对于web应用程序,默认行为是即使在用户关闭浏览器后也保持用户的会话。这是方便的,因为用户不需要每次在同一设备上访问网页时都连续登录。
因此,如果代码在浏览器中运行,则不需要调用setPersistence(auth, browserLocalPersistence)
。然而,您所做的需要的是,当Firebase恢复登录用户时,它会在您的代码中检测到。
在重新加载页面时恢复用户需要Firebase调用服务器,以检查帐户是否已被禁用。在进行该呼叫时,currentUser
将是null
。为了在用户恢复时得到通知,以及身份验证状态的其他更改,您需要使用身份验证状态侦听器,如获取当前用户的文档中的第一个代码片段所示:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
在这段代码中,您将调用setVentana("Tienda")
来导航到正确的窗口。
您可以使用redux持久化,所以如果重新加载页面,redux存储将持久化。这份文件我帮你https://react-redux-firebase.com/docs/integrations/redux-persist.html
实现redux w/toolkit(设置redux IMO的最简单方法(-您可以遵循本教程
重要提示是使用firebase包中可用的onAuthStateChanged
方法更新状态,而不是在登录/注册功能期间直接更改状态