React组件未显示在匹配的路由上(react-router-dom)

问题描述 投票:5回答:2

嘿大家我不知道发生了什么事。我有以下路线:

<BrowserRouter>
  <div>
    <Switch>
      <Route path="/patient/:id/" component={PatientWrapper} />
      <Route path="/patient/:id/patient_profile/admission_form" component={PatientAdmission} />
      <Route path="/patient/:id/patient_profile/discharge_form" component={PatientDischarge} />
      <Route path="/patient/:id/patient_profile/encounter_details" component={PatientEncounterDetails} />
      <Route path="/" component={App} />
    </Switch>
  </div>
</BrowserRouter>

只有Route = path /“/”和Route with path =“/ patient /:id”才有效,其他3个路径只是没有显示与路径对应的组件。

这就是我访问路线的方式。我有一个标题组件,上面有正确的链接。见下文

<ul className="dropdown-menu dropdown-messages">
    <li><Link to={"/patient/" + this.props.id +"/patient_profile/admission_form"} id="admission-link" >Admission</Link></li>
     <li><Link to={"/patient/" + this.props.id +"/patient_profile/discharge_form"} id="discharge-link">Discharge</Link></li>
     <li className="divider"></li>
     <li><Link to={"/patient/" + this.props.id +"/patient_profile/encounter_details"} id="encounter-details">Encounter Details</Link></li>
</ul>

在Header组件中,我从'react-router-dom'导入{Link};在我声明路由的文件中,我从'react-router-dom'导入{BrowserRouter,Route,Switch};

我究竟做错了什么?

reactjs react-router-dom
2个回答
1
投票

这里的问题是你没有使用exact道具为你的父路线。默认情况下,Route不会完全匹配。作为路径/的一个例子,//patient都被认为是匹配。因此,即使在您的情况下,/patient/:id/路线匹配从/patient/:id/开始的所有其他路线路径。由于Switch只渲染第一个匹配,因此它总是呈现PatientWrapper甚至是/patient/:id/patient_profile/admission_form等其他路径。

使用exact prop如下所示,您可以明确指示Route完全匹配。

<BrowserRouter>
  <div>
    <Switch>
      <Route exact path="/" component={App} />
      <Route path="/patient/:id/" exact component={PatientWrapper} />
      <Route path="/patient/:id/patient_profile/admission_form" component={PatientAdmission} />
      <Route path="/patient/:id/patient_profile/discharge_form" component={PatientDischarge} />
      <Route path="/patient/:id/patient_profile/encounter_details" component={PatientEncounterDetails} />
    </Switch>
  </div>
</BrowserRouter>

0
投票

确保在渲染路径时将其换行:

<BrowserRouter>
    <Switch>
       <Route path="/patient/:id/" component={PatientWrapper} />
      <Route path="/patient/:id/patient_profile/admission_form" component={PatientAdmission} />
      <Route path="/patient/:id/patient_profile/discharge_form" component={PatientDischarge} />
      <Route path="/patient/:id/patient_profile/encounter_details" component={PatientEncounterDetails} />
      <Route path="/" component={App} />
    </Switch>
</BrowserRouter>
© www.soinside.com 2019 - 2024. All rights reserved.