如何在不将其嵌套在现有组件中的情况下为单个主题渲染/路由该组件?

时间:2019-12-17 22:37:04

标签: reactjs react-router react-router-dom

好的,我正在尝试根据以下指南设置路由:https://reacttraining.com/react-router/web/guides/quick-start

第二个示例有一个主题列表,您可以选择,每个主题都有指向特定主题的主题组件的“路线”,但是我的问题是,它只是将主题组件呈现在主题列表的下面。如何仅获取主题以呈现到页面?我希望可用主题列表消失。

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useRouteMatch,
  useParams
} from "react-router-dom";

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/topics">Topics</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/topics">
            <Topics />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Topics() {
  let match = useRouteMatch();

  return (
    <div>
      <h2>Topics</h2>

      <ul>
        <li>
          <Link to={`${match.url}/components`}>Components</Link>
        </li>
        <li>
          <Link to={`${match.url}/props-v-state`}>
            Props v. State
          </Link>
        </li>
      </ul>

      {/* The Topics page has its own <Switch> with more routes
          that build on the /topics URL path. You can think of the
          2nd <Route> here as an "index" page for all topics, or
          the page that is shown when no topic is selected */}
      <Switch>
        <Route path={`${match.path}/:topicId`}>
          <Topic />
        </Route>
        <Route path={match.path}>
          <h3>Please select a topic.</h3>
        </Route>
      </Switch>
    </div>
  );
}

function Topic() {
  let { topicId } = useParams();
  return <h3>Requested topic ID: {topicId}</h3>;
}

1 个答案:

答案 0 :(得分:0)

您在“主” Switch上定义主题路由。

您还需要向exact /topics添加Route属性,以避免匹配/topics/1并删除Topics内的嵌套路由

<Switch>
  <Route exact path="/topics">
    <Topics />
  </Route>
  <Route path="/topics/:topicId">
    <Topic />
  </Route>
</Switch>
const Topics = () => (
  <div>
    <h1>Topics</h1>
    <Link to="/topics/1">Topic 1</Link>
    <Link to="/topics/2">Topic 2</Link>
    <Link to="/topics/3">Topic 3</Link>
  </div>
)
const Topic = () => {
  const { topicId } = useParams()

  return <h1>{topicId}</h1>
}