You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决React项目中基于登录态的路由重定向异常问题

问题根因
  • 你仅对/signIn路由做了登录状态判断,根路径/的路由没有添加任何鉴权逻辑,无论currentUser是否为null都会直接渲染首页,自然不会触发未登录重定向逻辑。
  • auth.onAuthStateChanged是异步回调,组件首次渲染时回调还未执行,你直接用初始值null做登录判断,会导致已登录用户首次访问时出现登录页闪屏再跳回首页的异常。
修复方案
  1. 新增加载状态标记鉴权结果是否返回,避免异步判断偏差
  2. 给根路径路由添加鉴权逻辑,未登录时重定向到登录页

修改后的代码如下:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 10:06:03