反应路由器更改URL,但不呈现视图

时间:2020-07-22 14:04:13

标签: reactjs typescript react-router

我正在做打字稿作业,这是医生用来添加患者,诊断等的应用程序。我正在使用react-router。路由器正在更改URL,但由于某些原因未呈现患者视图。我已经尝试了一段时间了。有人可以将我推向正确的方向吗?谢谢。

App.tsx

import React, { useState } from "react";
import axios from "axios";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import { Button, Divider, Header, Container } from "semantic-ui-react";

import { apiBaseUrl } from "./constants";
import { useStateValue } from "./state";
import { Patient } from "./types";

import PatientListPage from "./PatientListPage";
import PatientPage from "./components/PatientPage";

const App: React.FC = () => {
  //const [, dispatch] = useStateValue();

  const [{ patient }, dispatch] = useStateValue();
  const [page, setPage] = useState('');
  React.useEffect(() => {
    axios.get<void>(`${apiBaseUrl}/ping`);

    const fetchPatientList = async () => {
      try {
        const { data: patientListFromApi } = await axios.get<Patient[]>(
          `${apiBaseUrl}/api/patients`
        );
        dispatch({ type: "SET_PATIENT_LIST", payload: patientListFromApi });
      } catch (e) {
        console.error(e);
      }
    };
    fetchPatientList();
  }, [dispatch]);

  const showPatient = async (id: string) => {
    try {
      const { data: patientFromApi } = await axios.get<Patient>(`${apiBaseUrl}/api/patients/${id}`);
      
      dispatch({ type: "GET_PATIENT", payload: patientFromApi });
      setPage(patientFromApi.id);
      console.log('patient', patient);
    } catch (error) {
      console.log(error.message);
    }
  }

  return (
    <div className="App">
      <Router>
        <Container>
          <Header as="h1">Patientor</Header>
          <Button as={Link} to="/" primary>
            Home
          </Button>
          <Divider hidden />
          <Switch>
            <Route path="/">
              <PatientListPage showPatient={showPatient} />  
            </Route>
            <Route path={`/${page}`} >
              <PatientPage />
            </Route>
          </Switch>
        </Container>
      </Router>
    </div>
  );
};

export default App;

PatientListPage.tsx

import React from "react";
import axios from "axios";
import { Container, Table, Button } from "semantic-ui-react";

import { PatientFormValues } from "../AddPatientModal/AddPatientForm";
import AddPatientModal from "../AddPatientModal";
import { Patient } from "../types";
import { apiBaseUrl } from "../constants";
import HealthRatingBar from "../components/HealthRatingBar";
import { useStateValue } from "../state";
import { Link } from "react-router-dom";

const PatientListPage: React.FC<{ showPatient: any }> = ({ showPatient }) => {
  const [{ patients, patient }, dispatch] = useStateValue();

  const [modalOpen, setModalOpen] = React.useState<boolean>(false);
  const [error, setError] = React.useState<string | undefined>();

  const openModal = (): void => setModalOpen(true);

  const closeModal = (): void => {
    setModalOpen(false);
    setError(undefined);
  };

  const submitNewPatient = async (values: PatientFormValues) => {
    try {
      const { data: newPatient } = await axios.post<Patient>(
        `${apiBaseUrl}/api/patients`,
        values
      );
      dispatch({ type: "ADD_PATIENT", payload: newPatient });
      closeModal();
    } catch (e) {
      console.error(e.response.data);
      setError(e.response.data.error);
    }
  };

  return (
    <div className="App">
        <Container textAlign="center">
          <h3>Patient list</h3>
        </Container>
        <Table celled>
          <Table.Header>
            <Table.Row>
              <Table.HeaderCell>Name</Table.HeaderCell>
              <Table.HeaderCell>Gender</Table.HeaderCell>
              <Table.HeaderCell>Occupation</Table.HeaderCell>
              <Table.HeaderCell>Health Rating</Table.HeaderCell>
            </Table.Row>
          </Table.Header>
          <Table.Body>
            {Object.values(patients).map((patient: Patient) => (
              
              <Table.Row key={patient.id} onClick={() => showPatient(patient.id)}>
                <Link to={`/${patient.id}`}>
                  <Table.Cell>{patient.name}</Table.Cell>
                </Link>
                <Table.Cell>{patient.gender}</Table.Cell>
                <Table.Cell>{patient.occupation}</Table.Cell>
                <Table.Cell>
                  <HealthRatingBar showText={false} rating={1} />
                </Table.Cell>
              </Table.Row>
              
            ))}
          </Table.Body>
        </Table>
        <AddPatientModal
          modalOpen={modalOpen}
          onSubmit={submitNewPatient}
          error={error}
          onClose={closeModal}
        />
        <Button onClick={() => openModal()}>Add New Patient</Button>
    </div>
  );
};

export default PatientListPage;

PatientPage.tsx

import React, { useState } from "react";
import { Patient } from '../types';
import { useStateValue } from "../state";

const PatientPage: React.FC = () => {
  const [{ patient }, dispatch] = useStateValue();
  return (
    <>
      name: {patient.name}
      ssn: {patient.ssn}
      occupation: {patient.occupation}
    </>
  )
}

export default PatientPage

1 个答案:

答案 0 :(得分:0)

可能是因为您没有使用完全相同的关键字,所以它呈现了PatientListPage组件。

<Switch>
  <Route exact path="/">
    <PatientListPage showPatient={showPatient} />
  </Route>
  <Route path={`/${page}`}>
    <PatientPage />
  </Route>
</Switch>

更多信息here