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

IT技术 reactjs react-router-dom
2021-04-28 11:13:17

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

<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 with 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 };

我究竟做错了什么?

2个回答

这里的问题是您没有exact为父路由使用prop。默认情况下,Route 不会进行完全匹配。作为 path 的示例///patient都被视为匹配项。因此,即使在您的情况下,/patient/:id/Route 也与从/patient/:id/. 由于 Switch 仅呈现第一个匹配项,因此即使对于其他路径(如/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>

确保在渲染路由时将它们包装起来:

<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>