【问题标题】:Why does not work nested routes in react router?为什么反应路由器中的嵌套路由不起作用?
【发布时间】:2020-01-30 08:21:09
【问题描述】:

我尝试在反应应用程序中使用嵌套路由,但收到 404 页面。请帮忙。 首先,我尝试使用两个动态嵌套路由,但没有成功。接下来,我将第一个动态路由替换为静态,但还是不行。

App.jsx...

import { Home } from './components/Home';
import { About } from './components/About';
import { NotFound } from './components/404';
import { BrowserRouter, Route, Switch, Link } from 'react-router-dom';

const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/" exact>
           <Home />
        </Route>
        <Route path="/about" exact>
          <About />
        </Route>
        <Route component={NotFound} path={"*"} exact />
      </Switch> 
    </BrowserRouter> 
  );
}

关于.jsx

import React from 'react';
import { Link, Route, withRouter } from 'react-router-dom';
import Nested from './Nested';
import Switch from 'react-router/Switch';

const About = (props) => {
    return (
        <div>
        <Link to="/">Home</Link>
        <Link to={`${props.match.url}/id`}>Nested</Link>
        <Route path={`${props.match.url}/id`} component={Nested} />
        </div>
    )
}

const AboutWithRouter = withRouter(About)

export { AboutWithRouter as About }

【问题讨论】:

  • 您不应该将组件作为&lt;Route /&gt; 参数传递吗,例如&lt;Route path="/" exact component={Home} /&gt;?
  • 我不这样做吗????
  • 来自&lt;Route path="/" exact&gt;&lt;Home /&gt;&lt;/Route&gt;&lt;Route path="/about" exact&gt;&lt;About /&gt;&lt;/Route&gt; 部分代码,看起来你没有
  • 尝试将Route包装在About.jsx中的Switch中,如果是动态的,/id应该是/:id

标签: reactjs react-router


【解决方案1】:

您不需要在 NotFound 路由中包含 path="*"。省略路径将导致 Route 始终匹配。

  <Switch>
    <Route path="/" component={Home} />
    <Route path="/about" exact component={About} />
    <Route component={NotFound} />
  </Switch> 

【讨论】:

    【解决方案2】:

    不要在 Route 中使用子元素,而是使用 &lt;Route component&gt;。它将使用路由道具进行渲染。

    <Route path="/about"  component={About} />   
    

    temporary codesandbox

    【讨论】:

      猜你喜欢
      • 2015-11-25
      • 2017-10-27
      • 1970-01-01
      • 2019-02-18
      • 2016-08-18
      • 1970-01-01
      • 2019-01-12
      • 2017-08-06
      • 1970-01-01
      相关资源
      最近更新 更多