我的反应应用程序在加载正确的组件之前重定向到错误的组件

问题描述 投票:0回答:1

我有一个连接到 firebase 的 React 应用程序,它有 3 个角色。管理员用户和导师。我添加了代码来检查登录时的角色并根据角色进行适当的重定向。但是,即使我以用户身份登录,我也可以看到应用程序首先加载管理页面(打印的管理组件的日志语句),然后重定向到用户组件。如果我现在注销然后以作者身份登录,首先会安装管理组件,然后是用户组件,最后我会安装作者组件。我通过 console.log 语句来识别这一点。

代码如下。

export default function LoginSignup() { 
    const signIn = async (e) => { 
        e.preventDefault(); 
        if (email && password) { 
            await signInWithEmailAndPassword(firebaseAuth, email, password) 
                .then(async (user) => { 
                    const q = query(userCollection, where("email", "==", email)); 
                    const querySnapshot = await getDocs(q); 
                    querySnapshot.forEach((doc) => { 
                        console.log("//////////////" + doc.data().role);
                        setRole(doc.data().role); 
                        setUser(user.user);
                        if (doc.data().role == "admin") {
                          navigate("/admin");
                        } else if (doc.data().role == "user") {
                          navigate("/user");
                        } else if (doc.data().role == "author") {
                          navigate("/author");
                        } else {
                          console.log("role undefined");
                        }
                      });
                })
                .catch(async (error) => {
                      alert(error)
                });
                handlerEmail("");
                handlerPassword("");
          }
        }; 
} 

export default function AdminDashboard() { 
    useEffect(() => {
        onAuthStateChanged(firebaseAuth, (currentUser) => {
            if (currentUser) {
                console.log("admin dash");
                setUser(currentUser);
            } else 
                navigate("/");
        });
    }, []); 
}

因此,当我以管理员身份登录时,我会被重定向到管理员破折号。没有问题。

接下来,当我以用户身份登录时,首先打印 admin dash 的控制台语句,然后打印 //////////////" + user (loginsignup.jsx 的日志语句),然后打印 user仪表板组件已加载。

仅当我之前以其他角色登录时才会出现问题。如果我首先以用户身份登录,则不会发生这种情况。

以管理员身份登录,然后注销。然后以用户身份登录。在加载用户组件之前首先触发管理组件的 useEffect()

reactjs firebase firebase-authentication react-router
1个回答
0
投票

用户注销时需要清除用户和角色状态:

export default function AdminDashboard() { 
    useEffect(() => {
        onAuthStateChanged(firebaseAuth, (currentUser) => {
            if (currentUser) {
                console.log("admin dash");
                setUser(currentUser);
            } else {
                setUser(undefined); // 👈 or whatever indicates that there is no user to your app
                setRole(""); // 👈 or whatever value indicates no role
                navigate("/");
            }
        });
    }, []); 
}

在不清除角色的情况下,新用户最初将具有先前用户的角色 - 直到您从数据库加载他们自己的角色值。

© www.soinside.com 2019 - 2024. All rights reserved.