gpt4 book ai didi

reactjs - React Authentication Context 最初为空

转载 作者:行者123 更新时间:2023-12-03 21:54:13 25 4
gpt4 key购买 nike

我正在使用 React 上下文来保存我的应用程序的身份验证状态。目前,我遇到了一个问题,每当我尝试点击 /groups/:id ,它总是将我重定向到 /login先到/UserDash .发生这种情况是因为我的 AuthProvider 的上下文更新速度不够快,而我的 Private Route 使用 AuthContext 来决定是否重定向。

<AuthProvider>
<Router>
<Switch>
<LoggedRoute exact path = "/" component = {Home}/>
<Route exact path = "/login" component = {Login}/>
<PrivateRoute exact path = "/groups/:id" component = {GroupDash}/>
<PrivateRoute exact path = "/UserDash" component = {UserDash}/>
</Switch>
</Router>
</AuthProvider>

在另一个文件中:
export const AuthContext = React.createContext();

export const AuthProvider = ({children}) => {
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
firebaseApp.auth().onAuthStateChanged(setCurrentUser);
},[]);
return (
<AuthContext.Provider
value = {{currentUser}}
>
{children}
</AuthContext.Provider>
);

我的私有(private)路线:
const PrivateRoute = ({component: RouteComponent, ...rest}) => {
const {currentUser} = useContext((context) => AuthContext);
return (
<Route
{...rest}
render={routeProps => (currentUser) ? (<RouteComponent{...routeProps}/>) : (<Redirect to={"/login"}/>)}
/>
)
};

还有我的登录页面
 const {currentUser} = useContext(AuthContext);
if (currentUser) {
return <Redirect to = "/UserDash" />
}
return (
<button onClick={(e) => {googleLogin(history)}}>Log In</button>
);

在私有(private)路由将用户重定向到登录页面之前,有什么方法可以强制加载上下文?我尝试在我的 PrivateRoute 中使用 firebase.auth().currentUser ,但这也失败了,我仍然被重定向到 "/login" , 在被推送到 "/UserDash" 之前.

最佳答案

由于 useEffect 在渲染之后运行,并且在 useEffect 中获取的值来自异步调用,因此可以做的是实际保持加载状态,直到数据可用为止

export const AuthContext = React.createContext();

export const AuthProvider = ({children}) => {
const [currentUser, setCurrentUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
firebaseApp.auth().onAuthStateChanged((user) => {
setCurrentUser(); setIsLoading(false)
});
},[]);
return (
<AuthContext.Provider
value = {{currentUser, isLoading}}
>
{children}
</AuthContext.Provider>
);
}

然后在 privateRoute
const PrivateRoute = ({component: RouteComponent, ...rest}) => {
const {currentUser, isLoading} = useContext((context) => AuthContext);
if(isLoading) return <div>Loading...</div>
return (
<Route
{...rest}
render={routeProps => (currentUser) ? (<RouteComponent{...routeProps}/>) : (<Redirect to={"/login"}/>)}
/>
)
};

关于reactjs - React Authentication Context 最初为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62078976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com