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

Django与React:登录成功后如何重定向至主页

解决登录成功后重定向至主页的问题

要实现登录验证成功后的重定向,你需要借助React Router的路由导航能力,同时完善登录逻辑的成功判断。以下是具体修改步骤:

1. 导入React Router相关依赖

确保项目已安装react-router-dom,然后在Login组件文件顶部导入withRouter高阶组件:

import { withRouter } from 'react-router-dom';

2. 完善登录逻辑与重定向

修改login方法,在获取到后端返回的token后确认登录成功,再通过props.history.push跳转到主页。同时修复直接修改state对象的不规范写法:

login = event => {
  fetch('http://127.0.0.1:8000/auth/', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(this.state.credentials)
  })
  .then(data => data.json())
  .then(data => {
    // 后端返回token即视为登录成功
    if (data.token) {
      this.props.userLogin(data.token);
      // 跳转到主页,路径根据你的路由配置调整,比如'/'或'/home'
      this.props.history.push('/');
    } else {
      // 处理登录失败场景,比如提示用户凭据无效
      console.error('登录失败:用户名或密码错误');
    }
  })
  .catch(error => console.error('登录请求出错:', error))
}

// 修复inputChanged方法,避免直接修改原state对象
inputChanged = event => {
  const cred = {...this.state.credentials};
  cred[event.target.name] = event.target.value;
  this.setState({credentials: cred});
}

3. 用withRouter包装组件

在组件导出时,使用withRouter包装Login组件,让组件能获取到history对象:

export default withRouter(Login);

可选:注册成功后的重定向

如果需要注册成功后跳转页面,可在register方法中添加相同逻辑:

register = event => {
  fetch('http://127.0.0.1:8000/api/users/', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(this.state.credentials)
  })
  .then(data => data.json())
  .then(data => {
    if (data.token) {
      console.log(data.token);
      // 注册成功后跳转到主页或登录页
      this.props.history.push('/');
    }
  })
  .catch(error => console.error('注册请求出错:', error))
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:01:26