如何在不影响其他用户的个人资料的情况下向用户的个人资料添加数据 React

安吉

当用户被点击时,它会转到他/她的个人资料页面。单击个人资料页面上的备注标签,用户可以在他/她的个人资料中添加备注。但是现在当任何用户添加注释时,注释也会出现在其他用户的个人资料中。如何使添加的注释仅出现在添加注释的用户个人资料中?

    import React, { useState, useEffect } from "react";
    import { Switch, Route } from "react-router-dom";
    import PatientsTable from "./components/PatientsTable";
    import EditPatient from "./components/EditPatient";
    
    function App() {
      const [patients, setPatients] = useState([]);
      const [notes, setNotes] = useState([]);
      const finalDraftNotes = notes.filter((note) => note.isFinal === true);
    
      const fetchPatients = async () => {
        const response = await fetch("http://localhost:3000/users");
        const results = await response.json();
        setPatients(results);
      };
    console.log(notes)
      useEffect(() => {
        fetchPatients();
      }, []);
    
      const handleAddNote = (note) => {
        setNotes((prev) => [note, ...prev]);
      };
    
      const deleteDraftClick = (draftId) => {
        setNotes((prev) => prev.filter((draft) => draft.id !== draftId));
      };
    
      const saveNotesClick = () => {
        setNotes((prev) =>
          prev.map((note) => {
            return {
              ...note,
              isFinal: true,
            };
          })
        );
      };
    
      return (
        <>
          <Switch>
            <Route exact path="/">
              <PatientsTable patients={patients} />
            </Route>
            <Route path="/patient/:id">
              <EditPatient
                patients={patients}
                notes={notes}
                handleAddNote={handleAddNote}
                deleteDraftClick={deleteDraftClick}
                saveNotesClick={saveNotesClick}
                finalDraftNotes={finalDraftNotes}
              />
            </Route>
          </Switch>
        </>
      );
    }
    
    export default App;
    import React from "react";
    import { Link } from "react-router-dom";
    import {
      makeStyles,
      Table,
      TableBody,
      TableCell,
      TableContainer,
      TableHead,
      TableRow,
      Paper,
    } from "@material-ui/core";
    
    const useStyles = makeStyles({
      tableContainer: {
        width: 700,
        margin: "20px auto",
      },
      tableHead: {
        backgroundColor: "rgb(25,118,210)",
      },
      tableRow: {
        textDecoration: "none",
      },
    });
    
    export default function PatientsTable({ patients, selectPatientClick }) {
      const styles = useStyles();
      return (
        <TableContainer className={styles.tableContainer} component={Paper}>
          <Table aria-label="simple table">
            <TableHead className={styles.tableHead}>
              <TableRow>
                <TableCell>First Name</TableCell>
                <TableCell align="right">Last name</TableCell>
                <TableCell align="right">DOB</TableCell>
                <TableCell align="right">Phone Number</TableCell>
                <TableCell align="right">Email</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {patients.map((patient) => (
                <TableRow
                  component={Link}
                  to={`/patient/${patient.id}`}
                  onClick={selectPatientClick}
                  key={patient.id}
                  className={styles.tableRow}
                >
                  <TableCell component="th" scope="row">
                    {patient.fName}
                  </TableCell>
                  <TableCell align="right">{patient.lName}</TableCell>
                  <TableCell align="right">{patient.dob}</TableCell>
                  <TableCell align="right">{patient.pNumber}</TableCell>
                  <TableCell align="right">{patient.email}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      );
    }
    import React, { useState } from "react";
    import { useParams } from "react-router-dom";
    import { formatAMPM, generateId } from "../helper";
    
    import { makeStyles, Button, TextField } from "@material-ui/core";
    import AccountBoxIcon from "@material-ui/icons/AccountBox";
    
    const useStyles = makeStyles({
      form: {
        display: "flex",
        flexDirection: "column",
      },
      textFiled: {
        width: 300,
      },
      btnsContainer: {
        width: 300,
        margin: "20px 0",
        display: "flex",
        justifyContent: "space-between",
      },
    });
    
    export default function AddNote({ addNote }) {
      const styles = useStyles();
      const { id } = useParams();
      const [note, setNote] = useState(null);
      console.log(id);
      const handleInputChange = ({ target }) => {
        setNote(target.value);
      };
    
      const handleSubmitClick = (e) => {
        e.preventDefault();
    
        const newNote = {
          userPic: <AccountBoxIcon color="primary" fontSize="large" />,
          user: "Test User",
          time: formatAMPM(new Date()),
          note: note,
          id: generateId(),
          isFinal: false,
        };
    
        if (note) {
          addNote(newNote);
        }
        setNote("");
      };
    
      const handleClearNoteClick = () => {
        setNote("");
      };
    
      return (
        <>
          <form className={styles.form} onSubmit={handleSubmitClick}>
            <TextField
              className={styles.textFiled}
              label="note"
              multiline
              variant="outlined"
              rowsMax={Infinity}
              onChange={handleInputChange}
              placeholder="add a note"
              value={note}
            />
            <div className={styles.btnsContainer}>
              <Button
                label="add note"
                variant="contained"
                color="primary"
                type="sbumit"
              >
                add note
              </Button>
              <Button
                onClick={handleClearNoteClick}
                variant="contained"
                color="secondary"
              >
                clear note
              </Button>
            </div>
          </form>
        </>
      );
    }
    import React from "react";
    import { makeStyles, Button } from "@material-ui/core";
    
    export default function Notes({ note, draftIdToDelete }) {
      const styles = useStyles();
    
      const deleteDraftClick = () => {
        draftIdToDelete(note.id);
      };
    
      return (
        <li className={styles.note}>
          <span>{note.userPic}</span>
          <div className={styles.noteDetails}>
            <span>{note.user}</span>
            <span className={styles.time}>{note.time}</span>
            <span>{note.note}</span>
          </div>
          {!note.isFinal ? (
            <Button
              size="small"
              variant="contained"
              color="secondary"
              type="delete"
              className={styles.deleteBtn}
              onClick={deleteDraftClick}
            >
              delete draft
            </Button>
          ) : null}
        </li>
      );
    }
    

    import React from "react";
    import AddNote from "./AddNote";
    import Notes from "./Notes";
    import {
      useParams,
      Link,
      Route,
      useRouteMatch,
      Switch,
    } from "react-router-dom";
    
    
    import {
      makeStyles,
      Button,
      Typography,
      Card,
      CardContent,
    } from "@material-ui/core";
    
    const useStyles = makeStyles({
      card: {
        width: "70%",
        margin: "auto",
        minHeight: 600,
        position: "relative",
      },
      edit: {
        backgroundColor: "rgb(63,81,181)",
        display: "flex",
        justifyContent: "space-between",
        padding: 16,
        color: "white",
      },
      btnsContainer: {
        margin: "20px 0",
      },
      saveBtn: {
        width: 140,
        position: "absolute",
        bottom: 10,
        right: 10,
      },
    });
    
    export default function EditPatient({
      notes,
      handleAddNote,
      deleteDraftClick,
      saveNotesClick,
      finalDraftNotes,
    }) {
      const styles = useStyles();
      const { id } = useParams();
      let match = useRouteMatch();
    
      return (
        <Card className={styles.card}>
          <CardContent>
            <div className={styles.edit}>
              <Typography variant="h5">Edit Patient</Typography>
              <Button color="white" component={Link} to="/">
                X
              </Button>
            </div>
            <div className={styles.btnsContainer}>
              <Button
                color="primary"
                component={Link}
                to={`${match.url}/details`}
              >
                Detials
              </Button>
              <Button
                color="primary"
                component={Link}
                to={`${match.url}/notes`}
              >
                Notes ({finalDraftNotes.length})
              </Button>
            </div>
            <Switch>
              <Route path={`${match.path}/notes`}>
                <div>
                  <AddNote addNote={handleAddNote} />
                  <ul>
                    {notes && notes.map((note) => (
                      <Notes
                        key={note.id}
                        note={note}
                        draftIdToDelete={deleteDraftClick}
                      />
                    ))}
                  </ul>
                </div>
              </Route>
              <Route path={`${match.path}/details`}>
                <p>{id}</p>
              </Route>
            </Switch>
          </CardContent>
          <Button
            component={Link}
            to="/"
            onClick={saveNotesClick}
            className={styles.saveBtn}
            variant="contained"
            color="primary"
          >
            save & close
          </Button>
        </Card>
      );
    }

布他林

你有一个非常复杂的代码,但我试图理解你的观点......最后哦,好吧,所以每个病人都必须有自己的笔记,你必须首先将病人 id 添加到每个笔记对象,这样做是通过获取id 参数(你已经这样做了,并将其传递给 AddNote 组件:

export default function EditPatient({//...})
  //.....
const { id } = useParams();
 //.....
<AddNote addNote={handleAddNote} idPatient={id} />

现在,转到您的AddNote组件,我们需要将患者 ID 添加到注释对象中,如下所示:

export default function AddNote({ addNote, idPatient }) {
/...
const newNote = {
          userPic: <AccountBoxIcon color="primary" fontSize="large" />,
          user: "Test User",
          time: formatAMPM(new Date()),
          note: note,
          id: generateId(),
          isFinal: false,
          idPatient: idPatient //<----add it here
        };

现在,剩下要做的是根据 idPatient 过滤每个患者档案的注释,回到 EditPatient 组件:

export default function EditPatient({
   //....
const { id } = useParams();
notes = notes.filter((note)=> note.idPatient === id)

PS:当你做得很好时,你让你的代码变得如此复杂和不可读,所以我的建议使用状态管理工具,比如 Context api 或 redux 来让你的代码更干净和易于维护,而不是顶级 useState()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React Native,更新用户个人资料图片

如何在Django中链接到其他用户的个人资料?

如何在Django上编辑其他用户个人资料

其他用户的个人资料未显示,仅显示当前用户名。如何显示其他用户的个人资料?

如何防止用户访问其他用户的个人资料?

其他用户如何在 octobercms 中查看用户的个人资料详细信息?

如何在我的PHP代码中设置个人资料名称或其他用户名

如何在流星中获取其他用户的个人资料详细信息

将头像(用户个人资料照片)添加到语义UI React的下拉菜单中

登录的用户正在访问其他用户个人资料

在django中以其他用户身份查看个人资料页面

C#Selenium使用其他用户个人资料启动Chrome

导航到其他用户的个人资料(laravel 5.2)

防止在 django 中编辑其他用户的个人资料

Android studio 如何让查看某人个人资料的其他用户的可见性消失 Firebase

如何在Joomla用户个人资料编辑表单上添加其他字段?

如何在其他组件中显示单击的用户个人资料数据?

两个单独的模板个人资料页面供用户本人和其他用户使用?

react-native-deck-swiper 触摸以查看个人资料

默认个人资料图片 - MicrosoftGraph、React

如何通过简单地更改 url 中的 id 来防止登录用户访问其他用户的个人资料,在 django 中?

如何使用React Native Facebook SDK GraphRequest获得高质量的个人资料图片?

如何在导航栏中添加用户个人资料页面,在 oracle Apex 的注销按钮下

给定用户在Firestore中具有用户个人资料的情况下,如何检查用户是否存在

用户个人资料服务

用户个人资料照片

用户个人资料图片

如何为特定用户添加新的个人资料?

如何在Django上链接到用户的个人资料