From 7680ae53a3a679dd053f8b77703adcf9e9b1a8a4 Mon Sep 17 00:00:00 2001 From: fyah Date: Sat, 9 May 2026 13:54:09 +0800 Subject: [PATCH] =?UTF-8?q?PWA=E5=AF=B9=E8=AF=9D=E6=8C=81=E4=B9=85?= =?UTF-8?q?=E5=8C=96=EF=BC=9AlocalStorage=EF=BC=8C=E5=88=B7=E6=96=B0?= =?UTF-8?q?=E4=B8=8D=E4=B8=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PWA/src/App.tsx | 54 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 13 deletions(-) diff --git a/PWA/src/App.tsx b/PWA/src/App.tsx index 0217f4f..d441ec1 100644 --- a/PWA/src/App.tsx +++ b/PWA/src/App.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useState, useEffect, useRef } from 'react' import ChatArea from './components/ChatArea' import InputArea from './components/InputArea' @@ -9,26 +9,40 @@ export type Message = { } const API = 'http://localhost:3001/api/chat' +const STORAGE_KEY = 'shenyan-messages' -let nextId = 0 +function loadMessages(): Message[] { + try { + const raw = localStorage.getItem(STORAGE_KEY) + return raw ? JSON.parse(raw) : [] + } catch { + return [] + } +} + +let nextId = (loadMessages().reduce((max, m) => Math.max(max, m.id), 0) || 0) + 1 export default function App() { - const [messages, setMessages] = useState([]) + const [messages, setMessages] = useState(loadMessages) const [loading, setLoading] = useState(false) + const didLoad = useRef(false) + + useEffect(() => { + if (!didLoad.current) { didLoad.current = true; return } + localStorage.setItem(STORAGE_KEY, JSON.stringify(messages)) + }, [messages]) const handleSend = async (text: string) => { const userMsg: Message = { id: nextId++, role: 'user', text } - setMessages((prev) => [...prev, userMsg]) + const updated = [...messages, userMsg] + setMessages(updated) setLoading(true) try { - const apiMessages = [ - ...messages.map((m) => ({ - role: m.role === 'user' ? 'user' : 'assistant', - content: m.text, - })), - { role: 'user', content: userMsg.text }, - ] + const apiMessages = updated.map((m) => ({ + role: m.role === 'user' ? 'user' : 'assistant', + content: m.text, + })) const res = await fetch(API, { method: 'POST', @@ -46,10 +60,24 @@ export default function App() { } } + const handleClear = () => { + setMessages([]) + localStorage.removeItem(STORAGE_KEY) + } + return (
-
- 沈晏 +
+ 沈晏 + {messages.length > 0 && ( + + )}