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

React中如何实现页面重定向?a标签与路由跳转均失效如何解决

问题原因&修复方案

你当前使用的是react-router-dom v6版本,存在两个核心错误导致跳转失效:

  • 路由配置语法错误:v6版本中<Route>组件渲染页面的属性已从component改为element,需要传入组件实例而非组件构造函数
  • 缺少跳转触发逻辑:目前提供的DefineDestino组件中的按钮没有绑定任何跳转逻辑,也未声明对应的<Link>标签或路由跳转方法调用

修复后的代码示例

1. App.js 修改

import Origem from './components/Origem';
import Destino from './components/Destino'
import './styles/App.css';
import React, {useState} from "react"
import EstadosOrigem from './components/Origem';
import EstadosDestino from './components/Destino';
import DefineDestino from './components/DefineDestino';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import CheckOut from './CheckOut';

function App() {
  return (
    <Router>
      <div className="App">
        <div className="mainContent">
          <h1>Escolha um destino.</h1>
          <EstadosOrigem />
          <EstadosDestino />
          <DefineDestino />
          <Routes>
            {/* 修正Route属性写法 */}
            <Route path="/CheckOut" element={<CheckOut />} />
          </Routes>
        </div>
      </div>
    </Router>
  );
}

export default App;

2. DefineDestino.js 修改(增加跳转逻辑)

如果需要点击购买按钮完成计算后自动跳转,用useNavigate方法实现:

import React, {useState} from "react"
// 导入跳转方法
import { useNavigate, Link } from "react-router-dom"
import CheckOut from "../CheckOut"

export default function DefineDestino(props) {
    const [initialValue, setValue] = useState(0)
    // 初始化跳转实例
    const navigate = useNavigate()

    const increment = () => {
        return {
            type:'counter/increment'
        }
    }

    function estadosReducer(state, action) {
        if (state === 'Rio de Janeiro' && action.type === 'counter/increment') {
            setValue(initialValue + 1000)
            // 完成逻辑后跳转
            navigate('/CheckOut')
        }
    }

    return(
        <div>
            <h1>Valor: {initialValue}</h1>
            <button onClick={() => estadosReducer(props.data, increment())}>Efetuar Compra</button>
            {/* 路由跳转按钮方案 */}
            <Link to="/CheckOut"><button>Link方式跳转</button></Link>
            {/* a标签跳转方案(会触发整页刷新,不推荐站内使用) */}
            <a href="/CheckOut"><button>a标签跳转</button></a>
        </div>
    )
}

3. CheckOut.js 无需修改,可正常使用


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:15:02