繁体   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");
  };

function fetchNotes在将 json 发送到setNote时被反复调用。 但是,如果 json 未发送到setNote ,则不会发生此类事情。

注释组件

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} />;
      })}
    </>
  );
};

可能的原因是什么,如何解决?

您可以修改我提供的代码并尝试一下,

注释组件

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} />;
      })}
    </>
  );
};

在我看来,当您第一次加载组件时,您只想从本地存储中获取笔记。 您现在没有在 useEffect function 中指定第二个参数,这意味着只要组件中发生任何 state 更改,就会获取注释。 如果您在 useEffect 中使用“[]”作为第二个参数,则只会在组件第一次加载时获取您的注释,而不是每次 state 更改时获取。

暂无
暂无

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

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