You need to enable JavaScript to run this app. React中onClick触发后react-router-dom的Redirect组件不生效问题
优惠活动
大模型
产品
解决方案
定价
更多

React中onClick触发后react-router-dom的Redirect组件不生效问题

问题核心原因

<Redirect> 是 声明式路由组件,仅当它被作为组件返回值渲染到React渲染树时才会触发跳转逻辑。你在点击事件回调函数中直接书写该JSX语句,既没有返回该组件,也没有将其挂载到渲染树中,执行后会被直接丢弃,因此无法触发跳转。

解决方案

方案1:使用编程式跳转API(事件回调场景推荐)

事件回调场景下优先使用编程式跳转API,不同版本react-router-dom写法如下:

react-router-dom v5 写法

使用useHistory钩子获取history实例调用跳转方法:

import { useHistory } from 'react-router-dom'

// 组件内部代码
const history = useHistory()
const getCourse = () => {
  console.log('gg');
  history.push(`/courses/${id}`)
}

react-router-dom v6 写法

v6版本移除了useHistory,替换为useNavigate:

import { useNavigate } from 'react-router-dom'

// 组件内部代码
const navigate = useNavigate()
const getCourse = () => {
  console.log('gg');
  navigate(`/courses/${id}`)
}

方案2:使用声明式跳转

如果需要使用声明式写法,可通过状态变量控制跳转组件的渲染:

import { useState } from 'react'
import { Redirect } from 'react-router-dom'
// 若为v6版本,替换为 import { Navigate } from 'react-router-dom'

// 组件内部代码
const [shouldRedirect, setShouldRedirect] = useState(false)

const getCourse = () => {
  console.log('gg');
  setShouldRedirect(true)
}

// 组件渲染逻辑最前面添加判断
if (shouldRedirect) {
  return <Redirect to={`/courses/${id}`} />
  // 若为v6版本,替换为 return <Navigate to={`/courses/${id}`} replace />
}

// 原有渲染逻辑保持不变
return (
  <div className="menu__course" onClick={() => getCourse()}>
    {/* 原有内容 */}
  </div>
)

注意:react-router-dom v6版本已经完全移除了<Redirect>组件,声明式跳转请使用<Navigate>组件替代。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 10:45:01