【问题标题】:How can I update updateNotes first then getNotes?如何先更新 updateNotes 然后再更新 getNotes?
【发布时间】:2021-11-04 07:22:56
【问题描述】:

这里先记录getNotes,然后记录updateNotes

有没有办法先updateNotes 然后getNotes?因为当我编辑并单击左箭头图标时,除非我刷新页面,否则它不会更新更改。

这是来自 NotesPage.js 的代码

const NotesPage = () => {
  const [notes, setNotes] = useState([]);
  
  useEffect(() => {
    getNotes();
    console.log('Log from getNotes');
  }, [])

  const getNotes = async () => {
    const response = await fetch("http://localhost:5000/notes");
    const data = await response.json()
    setNotes(data)
  }

这是来自 NotePage.js 的代码

function NotePage({ match, history }) {
  const noteId = match.params.id;
  const [note, setNote] = useState(null);

  useEffect(() => {
    getNote();
    console.log("Log from getNote");
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [noteId]);

  const getNote = async () => {
    if (noteId === 'new') return
    const response = await fetch(`http://localhost:5000/notes/${noteId}`);
    const data = await response.json();

    setNote(data);
  };

  const updateNote = async () => {
    await fetch(`http://localhost:5000/notes/${noteId}`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ ...note, "updated": new Date() }),
    });
    console.log("Log from updateNote");
  };

  const handeSubmit = () => {
    if (noteId !== "new" && !note.body) {
      deleteNote();
    } else if (noteId !== "new") {
      updateNote();
    } else if (noteId === 'new' && note !== null) {
      createNote()
    }
    history.push("/");
  };

【问题讨论】:

    标签: reactjs async-await react-hooks


    【解决方案1】:

    在完成所有其他操作后尝试 getNotes

    像这样:

    const handeSubmit = async () => {
      if (noteId !== "new" && !note.body) {
        await deleteNote();
      } else if (noteId !== "new") {
        await updateNote();
      } else if (noteId === "new" && note !== null) {
        await createNote();
      }
      getNote();
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2023-01-18
      • 1970-01-01
      • 2021-12-27
      • 2021-01-04
      相关资源
      最近更新 更多