react嵌套路由,并设置默认子路由

 

 

弄了好长时间,记得之前写的时候没问题呀,现在不知道哪里出现问题,后来才发现 是 exact  和 跳转子路由 路径的问题,哎

 

 

 

App.js

import React, {lazy, Suspense}  from "react";
import { Switch, Route } from 'react-router-dom';
function App() {
  return (
    <div className="App">
      <Suspense fallback={React.Fragment}>
        <Switch><Route path="/" exact component={lazy(() => import('./views/Login'))}>Route>
      
      // 切记!!!!!! 这里不能加 exact 否则子路由匹配不进去 <Route path="/MyService" component={lazy(() => import('./views/MyService'))}>Route>
<Route path="*" component={lazy(() => import('./views/Error/Error'))}>Route> Switch> Suspense> div> ); } export default App;

 

MyService/index.js
import React from 'react';
import { Switch, Route, useHistory } from 'react-router-dom';
import { Button } from 'antd-mobile';
// import routes from 'src/router';
import dent from './dent/dent'
import high from './high/high'

function MyService () {
  const history = useHistory()
  return (
    <div>
      MyService
    // !!!!!! 这里切记写上完整的路由路径,,即 父路由 + 子路由
<Button type="primary" onClick={() => history.push('/MyService/dent')}>AButton> <Button type="primary" onClick={() => history.push('/MyService/high')}>BButton> <Switch>
    
     // !!!!!! 这里切记写上完整的路由路径,,即 父路由 + 子路由
      <Route path="/MyService/dent" component={dent}>Route> 
      <Route path="/MyService/high" component={high}>Route>
    Switch>
   div>
  )
}

export default MyService;

 

MyService/dent/dent.jsx

import React from 'react';

function dent () {
  return (
    <div>
      dent
    div>
  )
}

export default dent;

 

MyService/high/high.jsx

import React from 'react';

function high () {
  return (
    <div>
      high
    div>
  )
}

export default high;

 

 

 

 

默写子路由 ,修改 MyService/index.js

import React from 'react';
import { Switch, Route, useHistory } from 'react-router-dom';
import { Button } from 'antd-mobile';
// import routes from 'src/router';
import dent from './dent/dent'
import high from './high/high'

function MyService () {
  const history = useHistory()
  return (
    <div>
      MyService
      <Button type="primary" onClick={() => history.push('/MyService/')}>AButton>
      <Button type="primary" onClick={() => history.push('/MyService/high')}>BButton>
      <Switch>
        <Route exact path="/MyService/" component={dent}>Route>
        <Route path="/MyService/high" component={high}>Route>
      Switch>
    div>
  )
}

export default MyService;

 

 

 

 

参考

https://www.cnblogs.com/yuyujuan/p/10140264.html

posted @ 2021-07-27 16:39  王希有  阅读(2753)  评论(0编辑  收藏  举报