简体   繁体   English

尽管使用“精确”,但React渲染多个组件

[英]React rendering multiple components despite using 'exact'

I have a React app with a conflict between two routes: 我有一个React应用程序,两条路线之间存在冲突:

<Route exact path="/app/participants/register" component={ParticipantRegistration}/>

<Route exact path="/app/participants/:participantID" component={ParticipantDetailed}/>

The first Route, renders fine. 第一条路线效果很好。 However, due to the /:participantID wildcard in the path of the second Route - both the ParticipantRegistration and ParticipantDetailed components render - despite using the exact parameter. 但是,由于第二条路径的路径中有/:participantID通配符,因此尽管使用了exact参数, ParticipantRegistrationParticipantDetailed组件均会呈现。

How can I get React to render only the ParticipantRegistration component when the path is /app/participants/register and not render the ParticipantDetailed component underneath? 我该如何反应仅渲染ParticipantRegistration当路径组件/app/participants/register ,而不是渲染ParticipantDetailed下面的组成部分?

I would prefer not to have to modify the paths as the app has a few other conflicts like this and keeping track of all the different paths is difficult enough as it is. 我宁愿不必修改路径,因为该应用程序还存在其他类似的冲突,因此很难跟踪所有不同的路径。

You can use a Switch to render only the one route at a time. 您可以使用“ Switch ”一次仅渲染一条路线。

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import "./styles.css";

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/x/register" component={() => <p>x</p>} />
        <Route path="/x/:id" component={() => <p>y</p>} />
      </Switch>
    </BrowserRouter>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You can play with the code here 您可以在此处使用代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM