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

React JS 项目登录成功后无法自动跳转欢迎页,需手动刷新如何解决?

修复步骤

1. 修正响应字段拼写错误

你在LoginForm.js的doLogin方法中,判断登录成功的字段存在拼写错误,你写的是succes,而后端返回的正确字段是success,因此登录成功后的状态更新逻辑永远不会触发,只有手动刷新页面时,App组件的componentDidMount生命周期会调用/isLoggedIn接口更新状态,才会跳转到欢迎页。

找到LoginForm.js中如下代码段:

let result = await res.json();
if (result && result.succes) {
  UserStore.isLoggedIn = true;
  UserStore.username = result.username;
}

else if (result && result.succes === false) {
  this.resetForm();
  alert(result.msg);
}

修改为:

let result = await res.json();
if (result && result.success) {
  UserStore.isLoggedIn = true;
  UserStore.username = result.username;
}

else if (result && result.success === false) {
  this.resetForm();
  alert(result.msg);
}

2. 确认MobX存储配置正确

如果你使用的是MobX 6及以上版本,需要确认/stores/UserStore.js中的状态字段被正确标记为可观察属性,否则被observer包裹的App组件无法感知到状态变化,不会自动重渲染:

import { makeObservable, observable } from 'mobx';

class UserStore {
  loading = true;
  isLoggedIn = false;
  username = '';

  constructor() {
    makeObservable(this, {
      loading: observable,
      isLoggedIn: observable,
      username: observable
    })
  }
}

export default new UserStore();

完成以上两步修改后,登录成功就会自动触发App组件重渲染,直接跳转到欢迎页。


内容的提问来源于stack exchange,提问作者mani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:09:00