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

MERN栈登录成功后无法保留user对象且跳转回登录页问题求助

问题根因

  • 核心问题是表单默认提交行为触发页面重载:你使用的提交按钮是type="submit"类型,放在Bootstrap的Form组件内部,点击时除了触发你自定义的login函数,还会触发表单原生提交逻辑,导致页面整体刷新,所有React内存中的状态(包括App组件存储的user信息)全部重置,同时表单参数会被拼接到URL后跳转到signin页,就是你看到的闪回现象。
  • 次要问题1:登录成功后的跳转路径错误,你写的history.push("/register")在路由配置中不存在,你要跳回首页需要改成/。
  • 次要问题2:首页路由当前的写法无法将user属性传递给Home组件。

修复步骤

1. 阻止表单默认提交行为

修改LoginForm/index.js中的login函数,新增事件阻止逻辑,同时修正跳转路径:

// 新增事件参数e
const login = (e) => {
    // 阻止表单默认提交刷新页面
    e.preventDefault()
    const { email, password } = user;
    if (email && password) {
        console.log("valid input", user);
        axios.post("http://localhost:4000/api/login", user)
            .then(response => {
                console.log(response.data);
                setLoginUser(response.data.user);
                // 改成跳转到首页,不要写不存在的/register
                history.push("/");
            })
            .catch(error => {
                console.error('There was an error!', error);
            });
    } else {
        alert('please enter all the fields');
    }
}

也可以同时把按钮的type从submit改成button,双重保险:

<Button variant="primary" type="button" onClick={login}>
  提交
</Button>

2. 修正首页路由,传递user属性给Home组件

修改App.js中首页的路由写法,用render属性代替component属性,才能传递自定义props:

<Route exact path='/' render={() => <Home user={user} />} />

3. (可选)添加登录状态持久化

如果希望页面刷新后仍然保持登录状态,可以将user信息存储到localStorage中:
修改App.js的状态初始化逻辑:

const [user, setLoginUser] = useState(JSON.parse(localStorage.getItem('loginUser')) || {})

登录成功时同时存储到localStorage:

setLoginUser(response.data.user);
localStorage.setItem('loginUser', JSON.stringify(response.data.user))

用户退出登录时调用localStorage.removeItem('loginUser')即可清除状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:48:01