【问题标题】:How do I render/route a component for individual Topic without nesting it in existing component?如何在不将其嵌套在现有组件中的情况下为单个主题渲染/路由组件?
【发布时间】:2020-04-10 11:30:38
【问题描述】:

好的,我正在尝试根据本指南设置路线: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>;
}

【问题讨论】:

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


    【解决方案1】:

    您在“主”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>
    }
    

    【讨论】:

    • 非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多