You need to enable JavaScript to run this app. react-router-dom中Redirect执行后无跳转无报错问题求助
优惠活动
大模型
产品
解决方案
定价
更多

react-router-dom中Redirect执行后无跳转无报错问题求助

问题根因

<Redirect> 组件*仅当被渲染到React的DOM树中时才会触发路由跳转,你在signIn回调函数中直接返回该组件,没有将其放入render函数的返回值中,React不会对其进行渲染,因此不会触发跳转逻辑,也不会产生报错。

可行解决方案

方案1:通过状态控制<Redirect>渲染

在state中新增登录状态标识,登录完成后修改状态,在路由区域渲染<Redirect>:

  • 新增state字段
constructor(){
  super();
  this.state = {
    windowWidth: window.innerWidth,
    navOpen: true,
    user: {
      id: '',
      name: '',
      email: ''
    },
    isLoginSuccess: false // 新增登录成功状态标识
  };
}
  • 修改signIn方法
signIn = (data) => {
  if(data){
    this.setState({
      user: {
        id: data.id,
        name: data.name,
        email: data.email
      },
      isLoginSuccess: true
    });
  }
}
  • 在路由区域渲染跳转逻辑
<Switch>
  {/* 登录成功后触发跳转 */}
  {this.state.isLoginSuccess && <Redirect to="/" />}
  <Route path="/" exact component={Home} />
  <Route path="/about" exact component={About} />
  <Route path="/contact" exact component={Contact} />
  <Route path='/catalogue' exact component={Catalogue} />
  <Route 
    path='/login' 
    exact 
    render={(props) => <Login {...props} signIn={this.signIn} onRouteChange={this.onRouteChange}/>}
  />
</Switch>

方案2:使用history对象命令式跳转

利用react-router提供的history对象直接调用跳转方法:

  • 修改login路由为render写法传递路由原生props
<Route 
  path='/login' 
  exact 
  render={(routeProps) => <Login signIn={this.signIn} onRouteChange={this.onRouteChange} {...routeProps}/>
/>
  • Login组件内调用signIn时传入history对象
// Login组件中登录成功的逻辑处
this.props.signIn(resData, this.props.history);
  • 修改signIn方法实现跳转
signIn = (data, history) => {
  if(data){
    this.setState({user: {
      id: data.id,
      name: data.name,
      email: data.email
    }});
    history.push('/');
  }
}
额外优化建议

你原有路由中使用component={() => <Home />}的写法会导致每次路由渲染时都创建新的组件实例,触发不必要的重渲染,无额外props传递时直接写component={Home}即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 13:36:04