React / React-Router - TypeError:无法读取未定义

时间:2017-06-14 15:49:10

标签: javascript reactjs react-router react-router-v4

我是一个React新手,试着创建我的第一个应用程序。到目前为止,我一直在尝试保持它非常简单,同时遵循一些教程和文档。

以下代码导致TypeError,如图所示 error screenshot

这是我的代码:

import React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'


const App = () => (
  <Router>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/hospitals">Find a Patient</Link></li>
      </ul>

      <hr/>

      <Route exact path="/" component={Home}/>
      <Route path="/hospitals" component={Hospitals}/>
    </div>
  </Router>
)

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

const HOSPITALS = [
  { id: 0, name: 'St James', patients: [
     { id: 1, location: 'Maple ward' },
     { id: 2, location: 'Birch ward' },
     { id: 3, location: 'Pine ward' }
  ]},
  { id: 1, name: 'Harrogate Hospital', patients: [
    { id: 4, location: 'Sycamore ward' },
    { id: 5, location: 'Fern ward' },
    { id: 6, location: 'Oak ward' }
  ]},
  { id: 2, name: 'Leeds General Infirmary', patients: [
    { id: 7, location: 'Trout ward' },
    { id: 8, location: 'Eel ward' },
    { id: 9, location: 'Salmon ward' }
  ]}
]

const find = (id) => HOSPITALS.find(p => p.id === id)


const Hospitals = ( {match} ) => {
  let hospitals = HOSPITALS.map((hospital) => {
    return (
      <li key={hospital.id}>
        <Link to={`${match.url}/${hospital.id}/patients`} >
          {hospital.name}
        </Link>
      </li>
    )
  });

  return (
    <div>
      <h2>Hospitals</h2>
      <ul>
        {hospitals}
      </ul>

      <hr/>

      <Route path={`${match.url}/:hospitalID/patients`} component={Patients}/>
    </div>
  )
}

const Patients = ( {match} ) => {
  const hospitalArray = find(match.params.hospitalID)

  let patients = hospitalArray.patients.map((patient) => {
    return (
      <li key={patient.id}>
        <Link to={`${match.url}/${patient.id}`} >
          {patient.location}
        </Link>
      </li>
    )
  });

  return (
    <div>
      <h2>Patient for {match.params.hospitalID}</h2>
      <ul>
        {patients}
      </ul>

      <hr/>

      <Route path={`${match.url}/:patientID`} component={PatientDetail}/>

    </div>
  )
}


const PatientDetail = ({match}) => (
  <div>
    <h2>Patient details for {match.params.patientID}</h2>
  </div>
)




export default App;

非常感谢任何帮助或见解。

谢谢!

0 个答案:

没有答案
相关问题