最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why am I getting this "Rendered more hooks than during the previous render" even though the useEf

programmeradmin3浏览0评论

Problem:

I'm encountering a "React has detected a change in the order of Hooks called by HomePage" error after refreshing my page. The error occurs specifically on the HomePage component. The application works as expected after logging in, but when I refresh the page, I receive the following error:

Title: React has detected a change in the order of Hooks called by HomePage

Problem:

I'm encountering a "React has detected a change in the order of Hooks called by HomePage" error after refreshing my page. The error occurs specifically on the HomePage component. The application works as expected after logging in, but when I refresh the page, I receive the following error:

HomePage.js:196
React has detected a change in the order of Hooks called by HomePage. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: /link/rules-of-hooks

Previous render Next render
useContext useContext
useEffect useEffect
useContext useContext
useState useState
useState useState
useState useState
useState useState
useContext useContext
useState useState
useState useState
useCallback useCallback
useEffect useEffect
useEffect useEffect
undefined useEffect 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
Error Component Stack at HomePage (HomePage.js:14:47) at App (_app.js:6:31)

Code:

Here's the relevant code snippet from my HomePage.js component:

useEffect(() => {
  if (!messages || messages.length === 0 || !session?.user?.id || !currentConversationId) {
      return; // Ensure useEffect exits early if dependencies are missing
  }

  const saveMessage = async () => {
      const lastMessage = messages[messages.length - 1];
      if (!lastMessage) return;

      try {
          await fetch(
              `http://localhost:3001/api/conversations/${currentConversationId}/messages`,
              {
                  method: "POST",
                  headers: { "Content-Type": "application/json" },
                  body: JSON.stringify({
                      userId: session.user.id,
                      sender: lastMessage.sender,
                      message: lastMessage.text,
                  }),
              }
          );
      } catch (error) {
          console.error("Error saving message:", error);
      }
  };

  saveMessage();
}, [messages, session?.user?.id, currentConversationId]); 



const handleSend = async () => {
  if (!input.trim()) return;

  const newMessage = { sender: "user", text: input };
  setMessages((prev) => [...prev, newMessage]);
  setInput("");

  try {
      let conversationId = currentConversationId;

      if (!conversationId) {
          const response = await fetch(
              "http://localhost:3001/api/conversations/new",
              {
                  method: "POST",
                  headers: { "Content-Type": "application/json" },
                  body: JSON.stringify({ userId: session.user.id }),
              }
          );

          if (!response.ok) throw new Error("Failed to create new chat");

          const data = await response.json();
          conversationId = data.id;

          setCurrentConversationId(conversationId);
          
          await new Promise((resolve) => setTimeout(resolve, 0));
      }

      const aiResponse = await fetch("http://localhost:3001/api/generate", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ prompt: input }),
      });

      const data = await aiResponse.json();
      const aiMessage = { sender: "ai", text: data.message };

      setMessages((prev) => [...prev, aiMessage]);
  } catch (error) {
      console.error("Error in handleSend:", error);
  }
};

I expected the saveMessageToDB function to wait for currentConversationId to be available before making the API call, ensuring messages were associated with the correct conversation.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论