简体   繁体   English

reactjs如何从数据库中获取新数据

[英]how get new data from database in reactjs

My projct is a note app where you can can add notes and delete notes.我的项目是一个笔记应用程序,您可以在其中添加笔记和删除笔记。 I want to get data from the database and show it but I have to delete note twice, add note or reload page to show the new data.我想从数据库中获取数据并显示它,但我必须删除两次便笺,添加便笺或重新加载页面以显示新数据。

notesList.jsx notesList.jsx
this is my main component这是我的主要组成部分
i send getNotes() to another component for i can get new datas我将 getNotes() 发送到另一个组件,以便我可以获取新数据

const NotesList = () => {
  const [notes, setNotes] = useState([]);

  const getNotes = async () => {
    const getNoteInformation = {
      email: localStorage.getItem("tokenEmail"),
    };
    const response = await axios.post(
      "http://localhost:9000/api/note/get",
      getNoteInformation
    );
    try {
      setNotes(response.data.data);
    } catch (error) {}
  };

  const handleAddNote = async (tasktext) => {
    const addNoteInformation = {
      email: localStorage.getItem("tokenEmail"),
      taskText: tasktext,
      date: moment(new Date()).locale("fa").format("YYYY/MM/DD").toString(),
    };

    if (addNoteInformation.email && addNoteInformation.taskText) {
      try {
        await axios.post(
          "http://localhost:9000/api/note/add",
          addNoteInformation
        );
      } catch (error) {}
    }
  };

  const handleDeleteNote = async (id) => {
    const deletedInformaion = {
      email: localStorage.getItem("tokenEmail"),
      noteId: id,
    };

    if (deletedInformaion.email && deletedInformaion.noteId) {
      await axios.post(
        "http://localhost:9000/api/note/deleted",
        deletedInformaion
      );
    }
  };

  useEffect(() => {
      getNotes();
  }, []);

  return (
    <>
      <Navbar />
      <div className="container">
        <div className="row">
          {notes
            .filter((notes) => notes != null)
            .map((notes, index) => (
              <Note
                key={index}
                text={notes.text}
                date={notes.date}
                id={notes._id}
                deletenote={handleDeleteNote}
                getnote={getNotes}
              />
            ))}
          <AddNote getnote={getNotes} addnote={handleAddNote} />
        </div>
      </div>
    </>
  );
};

note.jsx note.jsx

const Note = (props) => {
  const handleDeleteNote =  () => {
    props.deletenote(props.id);
    props.getnote();
  };

  return (
    <>
      <div className="col-lg-4 col-md-6 col-sm-12 p-4">
        <div className="note d-flex flex-column">
          <span className="note-top overflow-auto m-2 ps-2">{props.text}</span>
          <div className="note-bottom d-flex justify-content-between flex-row-reverse mt-auto">
            <small>{props.date}</small>
            <MdDelete
              onClick={handleDeleteNote}
              className="delete-icon"
              size="1.3rem"
              color="#bb86fc"
            />
          </div>
        </div>
      </div>
    </>
  );
};

addNote.jsx addNote.jsx

const AddNote = (props) => {
  let addNoteText = useRef();

  const handleAddNote = async () => {
    props.addnote(addNoteText.current.value);
    props.getnote();
    addNoteText.current.value = "";
  };

  return (
    <div className="col-lg-4 col-md-6 col-sm-12 p-4">
      <div className="add-note-box d-flex flex-column justify-content-between">
        <div className="top-box">
          <textarea
            placeholder="یادداشت خود را وارد کنید ......"
            class="form-control"
            rows={7}
            ref={addNoteText}
          ></textarea>
        </div>
        <BsFillPlusCircleFill
          onClick={handleAddNote}
          className="plus-icon"
          size="1.3rem"
          color="#bb86fc"
        />
      </div>
    </div>
  );
};

You didn't update state after sending the respective add and delete request, that's why you need to refresh to get the updated data.您在发送相应的adddelete请求后没有更新状态,这就是您需要刷新以获取更新数据的原因。 This is the fix:这是修复:

  const handleAddNote = async (tasktext) => {
    const addNoteInformation = {
      email: localStorage.getItem("tokenEmail"),
      taskText: tasktext,
      date: moment(new Date()).locale("fa").format("YYYY/MM/DD").toString(),
    };

    if (addNoteInformation.email && addNoteInformation.taskText) {
      try {
        await axios.post(
          "http://localhost:9000/api/note/add",
          addNoteInformation
        );
     
        setNotes([...notes, addNoteInformation]); // update state using spread operator and put the new one to the end
      } catch (error) {}
    }
  };

  const handleDeleteNote = async (id) => {
    const deletedInformaion = {
      email: localStorage.getItem("tokenEmail"),
      noteId: id,
    };

    if (deletedInformaion.email && deletedInformaion.noteId) {
      await axios.post(
        "http://localhost:9000/api/note/deleted",
        deletedInformaion
      );
      
      setNotes(notes.filter(note => note.id !== id)) // update state using filter function
    }
  };

Alternativelly, when adding notes, you can update state using the response object from your request, since the id of newly created note maybe generated by your database.或者,在添加注释时,您可以使用请求中的response object更新状态,因为新创建的注释的id可能由您的数据库生成。 It dependes on the actual response object from the axios request:它取决于来自 axios 请求的实际响应对象:

const response = await axios.post();
setNotes([...notes, response.data]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM