React 聊天机器人:在发送用户输入和获取 AI 响应时显示加载消息

问题描述 投票:0回答:1

我正在开发一个 React 聊天机器人,我想通过在发送用户输入和获取 AI 响应时显示加载消息来改善用户体验。目前,我已经实现了一条在实际 AI 响应之前出现的加载消息,但我面临着使加载首先出现在 AI 响应之前的问题。


const handleSendMessage = () => {
  console.log('handleSendMessage started');
  setAiIsLoading(true); // Set loading state to true
  
  if (inputMessage.trim() !== '') {
    const newMessage = {
      text: inputMessage,
      isUser: true,
    };
    setMessages((prevMessages) => [...prevMessages, newMessage]);

    fetch("http://localhost:8000/send_info", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ input: inputMessage }),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log('handleSendMessage fetch success');
        setAiIsLoading(false); // Set loading state to false

        if (data.just_gpt_result || typeof data.result === 'string' || typeof data.result === 'number' || data.result.chart_image_base64) {
          // If you received a valid response, update state with the AI response
          let chatbotResponseText;

          if (data.just_gpt_result) {
            chatbotResponseText = typeof data.just_gpt_result === 'object' ? JSON.stringify(data.just_gpt_result) : data.just_gpt_result;
          } else if (typeof data.result === 'string') {
            try {
              const jsonData = JSON.parse(data.result);
              const chatbotResponse = {
                component: <DataTable columns={jsonData.columns} data={jsonData.data} />,
                isUser: false,
              };
              setMessages((prevMessages) => [...prevMessages, chatbotResponse]);
              
            } catch (error) {
              console.error('Error parsing JSON:', error);
              chatbotResponseText = data.result;
            }
          } else if (typeof data.result === 'number' && Number.isInteger(data.result)) {
            chatbotResponseText = data.result;
          } else if (data.result.chart_image_base64) {
            const chartImageMessage = {
              component: (
                <img
                  src={`data:image/png;base64,${data.result.chart_image_base64}`}
                  alt="Chart Image"
                  className="chart-image"
                  style={{ maxWidth: '100%', height: 'auto' }}
                />
              ),
              isUser: false,
            };
            setMessages((prevMessages) => [...prevMessages, chartImageMessage]);
          } else {
            console.log('Received unsupported data:', data.result);
            chatbotResponseText = data.result;
          }

          const chatbotResponse = {
            text: chatbotResponseText,
            isUser: false,
          };
          setMessages((prevMessages) => [...prevMessages, chatbotResponse]);
        }
        setAiIsLoading(false); // Set loading state to false


      })
      .catch((error) => {
        console.error("Error sending user input:", error);
        setAiIsLoading(false); // Set loading state to false

      });

    setInputMessage('');
  }
};
<div className="chatbot-container">
  {messages.map((message, index) => (
    <div key={index} className={message.isUser ? "user-message" : "ai-message"}>
      {message.isUser ? (
        // ... (code for rendering user message)
      ) : (
        <>
          {/* Display loading message only for the latest AI message */}
          {index === messages.length - 1 && (
            <LoadingMessage>Loading...</LoadingMessage>
          )}

          {/* Display actual AI response when not loading */}
          {<>{message.text}</>}
        </>
      )}
    </div>
  ))}
</div>
reactjs chatbot loading
1个回答
0
投票

常量handleSendMessage = () => { console.log('handleSendMessage 开始'); setAiIsLoading(true); // 将加载状态设置为 true

if (inputMessage.trim() !== '') { 常量新消息 = { 文本:输入消息, 是用户:真实的, }; setMessages((prevMessages) => [...prevMessages, newMessage]);

fetch("http://localhost:8000/send_info", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ input: inputMessage }),
})
  .then((response) => response.json())
  .then((data) => {
    console.log('handleSendMessage fetch success');
    setAiIsLoading(false); // Set loading state to false

    if (data.just_gpt_result || typeof data.result === 'string' || typeof data.result === 'number' || data.result.chart_image_base64) {
      // If you received a valid response, update state with the AI response
      let chatbotResponseText;

      if (data.just_gpt_result) {
        chatbotResponseText = typeof data.just_gpt_result === 'object' ? JSON.stringify(data.just_gpt_result) : data.just_gpt_result;
      } else if (typeof data.result === 'string') {
        try {
          const jsonData = JSON.parse(data.result);
          const chatbotResponse = {
            component: <DataTable columns={jsonData.columns} data={jsonData.data} />,
            isUser: false,
          };
          setMessages((prevMessages) => [...prevMessages, chatbotResponse]);
          
        } catch (error) {
          console.error('Error parsing JSON:', error);
          chatbotResponseText = data.result;
        }
      } else if (typeof data.result === 'number' && Number.isInteger(data.result)) {
        chatbotResponseText = data.result;
      } else if (data.result.chart_image_base64) {
        const chartImageMessage = {
          component: (
            <img
              src={`data:image/png;base64,${data.result.chart_image_base64}`}
              alt="Chart Image"
              className="chart-image"
              style={{ maxWidth: '100%', height: 'auto' }}
            />
          ),
          isUser: false,
        };
        setMessages((prevMessages) => [...prevMessages, chartImageMessage]);
      } else {
        console.log('Received unsupported data:', data.result);
        chatbotResponseText = data.result;
      }

      const chatbotResponse = {
        text: chatbotResponseText,
        isUser: false,
      };
      setMessages((prevMessages) => [...prevMessages, chatbotResponse]);
    }
    setAiIsLoading(false); // Set loading state to false


  })
  .catch((error) => {
    console.error("Error sending user input:", error);
    setAiIsLoading(false); // Set loading state to false

  });

setInputMessage('');

} };

© www.soinside.com 2019 - 2024. All rights reserved.