如何解决React项目中基于登录态的路由重定向异常问题
问题根因
- 你仅对
/signIn路由做了登录状态判断,根路径/的路由没有添加任何鉴权逻辑,无论currentUser是否为null都会直接渲染首页,自然不会触发未登录重定向逻辑。 auth.onAuthStateChanged是异步回调,组件首次渲染时回调还未执行,你直接用初始值null做登录判断,会导致已登录用户首次访问时出现登录页闪屏再跳回首页的异常。
修复方案
- 新增加载状态标记鉴权结果是否返回,避免异步判断偏差
- 给根路径路由添加鉴权逻辑,未登录时重定向到登录页
修改后的代码如下:
class App extends React.Component { constructor() { super(); this.state = { currentUser: null, // 新增加载状态,标记是否已经拿到auth的登录态结果 authLoading: true }; } unsubscribeFromAuth = null; componentDidMount() { this.unsubscribeFromAuth = auth.onAuthStateChanged(user => { this.setState({ currentUser: user, authLoading: false // 拿到结果后关闭加载状态 }); }); } componentWillUnmount() { this.unsubscribeFromAuth(); } render() { // 鉴权中可以渲染加载动画,避免逻辑闪烁 if (this.state.authLoading) return <div>加载中...</div> console.log('Current state:', this.state); return ( <div className="App"> <Switch> <Route exact path="/" render={() => ( // 根路径添加鉴权,未登录直接跳转到登录页 this.state.currentUser ? <HomePage currentUser={this.state.currentUser} /> : <Redirect to="/signIn" /> )} /> <Route exact path="/signIn" render={() => (this.state.currentUser ? <Redirect to="/" /> : <SignInPage />)} /> </Switch> </div> ); } }
内容的提问来源于stack exchange,提问作者user14507093
相关产品推荐
相关产品推荐

