1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| import React, { useState, useEffect } from 'react';
function EcommerceChat() { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [sessionId, setSessionId] = useState(''); const [loading, setLoading] = useState(false);
useEffect(() => { initializeChat(); }, []);
const initializeChat = async () => { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: getUserId(), message: "你好,我想购物" }) }); const data = await response.json(); setSessionId(data.session_id); setMessages([ { role: 'assistant', content: data.response } ]); };
const sendMessage = async () => { if (!input.trim()) return;
setLoading(true);
const newMessages = [...messages, { role: 'user', content: input }]; setMessages(newMessages);
try { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: getUserId(), message: input, session_id: sessionId }) }); const data = await response.json();
setMessages([ ...newMessages, { role: 'assistant', content: data.response } ]); setInput(''); } catch (error) { console.error('Error:', error); } finally { setLoading(false); } };
return ( <div className="chat-container"> <div className="messages"> {messages.map((msg, idx) => ( <div key={idx} className={`message ${msg.role}`}> {msg.content} </div> ))} </div> <div className="input-area"> <input value={input} onChange={(e) => setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && sendMessage()} placeholder="输入您的问题..." /> <button onClick={sendMessage} disabled={loading}> {loading ? '发送中...' : '发送'} </button> </div> </div> ); }
export default EcommerceChat;
|