简体   繁体   English

React.js 获取请求 function 被重复调用

[英]React.js fetch request function getting called repetedly

const [notes, setNotes] = useState(notesInitial);

  //fetch notes
  const fetchNotes = async () => {
    const response = await fetch(
      "http://localhost:5500/api/notes/fetchallnotes",
      {
        method: "GET", // *GET, POST, PUT, DELETE, etc.

        headers: {
          "Content-Type": "application/json",
          "auth-token": localStorage.getItem("token"),
        },
      }
    );
    const json = await response.json();
    setNotes(json);
    console.log("Running Fetch all notes");
  };

The function fetchNotes is getting called repeatedly on sending the json to setNote . function fetchNotes在将 json 发送到setNote时被反复调用。 However no such thing is happening if the json is not send to the setNote .但是,如果 json 未发送到setNote ,则不会发生此类事情。

Notes Component注释组件

const Notes = () => {
  const context = useContext(noteContext);
  const { notes, fetchNotes } = context;
  let navigate = useNavigate();

  useEffect(() => {
    if (localStorage.getItem("token")) {
      fetchNotes();
    } else {
      navigate("/login");
    }
  });

  // console.log(notes);
  return (
    <>
      <h2>All Notes</h2>
      {notes.length === 0 && "No notes. Created note will appear here"}
      {notes.map((note) => {
        return <NoteItems note={note} key={note._id} />;
      })}
    </>
  );
};

What is the possible reason for it and how can it be solved?可能的原因是什么,如何解决?

You can modify the code as I'm providing and have a try,您可以修改我提供的代码并尝试一下,

Notes Component注释组件

const Notes = () => {
  const context = useContext(noteContext);
  const { notes, fetchNotes } = context;
  let navigate = useNavigate();
  const fetched = React.useRef(false); // +

  useEffect(() => {

    if (fetched.current === false) { // +

        if (localStorage.getItem("token")) {
          fetchNotes();
        } else {
          navigate("/login");
        }

        return () => { // +
            fetched.current = true; // +
        } // +


    } // +

  }, []); // +

  // console.log(notes);
  return (
    <>
      <h2>All Notes</h2>
      {notes.length === 0 && "No notes. Created note will appear here"}
      {notes.map((note) => {
        return <NoteItems note={note} key={note._id} />;
      })}
    </>
  );
};

It looks to me like you just want to fetch the notes from local storage when you first load the component.在我看来,当您第一次加载组件时,您只想从本地存储中获取笔记。 You aren't specifying the second parameter in your useEffect function right now, which means notes will be fetched whenever any state changes occur in the component.您现在没有在 useEffect function 中指定第二个参数,这意味着只要组件中发生任何 state 更改,就会获取注释。 If you use "[]" as the second parameter in useEffect, your notes will only be fetched when the component first loads , instead of every time the state changes. 如果您在 useEffect 中使用“[]”作为第二个参数,则只会在组件第一次加载时获取您的注释,而不是每次 state 更改时获取。

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

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