【问题标题】:How do I implement nested routing in react properly如何在正确反应中实现嵌套路由
【发布时间】:2020-11-11 16:08:25
【问题描述】:

这两天我都快疯了。请各位大侠帮忙。我正在尝试实现嵌套路由。但它不工作。当我转到 http://localhost:3000 时,它会正确显示。但是当我访问 http://localhost:3000/contact 时。它不起作用。我已经尽力了。请帮忙????

//App js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Main from './features/Main/Main';
import Dashboard from './features/Dashboard/Dashboard';
import Nomatch from './features/Nomatch';

function App() {

    return (
        <div>
            <Switch>
                <Route exact path='/'> <Redirect to='/home' /></Route>
                <Route path="/home" component={Main} />
                <Route path="/dashboard" component={Dashboard} />
                <Route component={Nomatch} />
            </Switch>
        </div>
    );

}

export default App;

//////////////////////////////////

//Main.js
import React from 'react';
import { Switch, Route, useRouteMatch } from 'react-router-dom';
import Home from './Home';
import Contact from './Contact';

const Main = () => {
const { path, url } = useRouteMatch();
    return(
        <div>
            <Switch>
                <Route exact path='/' component={Home} />
                <Route path={`${path}/contact`} component={Contact} />
            </Switch>
        </div>
    )

}

export default Main

【问题讨论】:

  • 我不想拥有 /home/contact。但是 /home , /contact /faq /dashboard。有没有可能
  • 你需要用路由器包裹Main的孩子

标签: reactjs routes nested


【解决方案1】:

更新

您可以尝试在 Main 中进行更改:

            <Switch>
                <Route exact path='/' component={Home} />
                <Route path={`${path}/contact`} component={Contact} />
            </Switch>

通过

            <Switch>
                <Route exact path='/home'><Redirect to='/' /></Route>
                <Route exact path='/' component={Home} />
                <Route exact path='/contact' component={Contact} />
            </Switch>

App

            <Switch>
                <Route path="/" component={Main} />
            </Switch>

【讨论】:

  • 我不想拥有 /home/contact。但是 /home , /contact /faq /dashboard。是否有可能 – user3118363 42 秒前编辑删除
  • 那你可以尝试在主应用中重定向,我会更新答案。
  • 好的。谢谢一堆。有效。我还决定使用字母“m”而不是“home”。我很感激你
猜你喜欢
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 2019-02-18
  • 2020-08-22
  • 2020-01-04
  • 2018-02-16
  • 2016-08-18
  • 1970-01-01
相关资源
最近更新 更多