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

React.js中Link Button路由跳转至其他组件失效问题求助

问题修复方案

核心问题定位

  • App.js中未正确导入使用React Router的Switch组件,路由匹配逻辑失效
  • Map组件中使用的是Material UI的普通Link组件,不支持React路由跳转
  • 表单校验逻辑未与跳转逻辑绑定,无校验直接跳转的逻辑不符合需求
  • 类组件未包裹withRouter,无法调用路由API实现编程式跳转

分步修复代码

1. 修复App.js路由配置

// 导入增加Switch组件,注意首字母大写
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

// 把原来的小写<switch>替换为大写<Switch>
<div className={classes.wrapper}>
  <Switch>
    <Route exact path="/">
      <Home/>
    </Route>
    <Route exact path="/About">
      <About/>
    </Route>
    <Route exact path="/Map">
      <Map/>
    </Route>
    <Route exact path="/PDF" >
      <PDF/>
    </Route>
  </Switch>
</div>

2. 修复Map组件路由跳转逻辑

// 导入React路由的withRouter
import { withRouter } from 'react-router-dom';

// 调整onSubmit逻辑,合并校验和跳转
onSubmit(e){
  e.preventDefault()
  // 执行校验逻辑
  if (!this.state.fname || !this.state.lname || !this.state.email) {
    alert(" All fields are required")
    return
  }
  // 校验通过后跳转
  this.props.history.push('/PDF')
}

// 调整Button组件,删掉原来的component和to属性,加上type="submit"
<Button
  fullWidth
  variant="contained"
  color="secondary"
  className={classes.submit}
  type="submit"
>
  Submit and Go to next
</Button>

// 导出时包裹withRouter,让组件能拿到history属性
export default withRouter(withStyles(useStyles, {withTheme:true}) (Map))

3. 可选优化:修复样式错误

原useStyles中所有带theme.spacing的属性都错误包裹了引号,改成直接调用即可:

const useStyles = (theme) => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
    alignItems:'center'
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(3),
  },
  submit: {
    margin: theme.spacing(3, 0, 2)
  },
});

后续操作

PDF组件可以直接从localStorage.getItem('user')读取已存储的表单数据,进行PDF生成和下载即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 06:21:01