我正在使用 Remix 创建一个简单的聊天应用程序。用户应输入一条消息,当单击提交按钮时,该消息将被发送到创建回复的后端。将消息发送到服务器工作正常,但如何在本地保存消息的副本以将其显示在聊天历史记录中?或者换句话说:如何在发送表单时访问表单值,同时仍然让 Remix 完成其工作?
这是我将聊天消息发送到服务器的代码:
// server side function
export async function action({
request,
}: ActionFunctionArgs) {
const formData = await request.formData();
const chatMessage = formData.get("chatMessage");
// generate chat reply on server side, no issue here
}
// client side code
<fetcher.Form method="post">
<input
type="text"
name="chatMessage"
placeholder="Enter your message"
/>
<button type="submit">
Send
</button>
</fetcher.Form>
// TODO: keep a history of sent messages on the client
您可以通过组合
useFetcher
、useState
和 useEffect
完全在客户端完成此操作,如下所示:
import { useFetcher } from '@remix-run/react'
import { useState, useEffect } from 'react'
/* ... */
export default function ChatRoute() {
const fetcher = useFetcher()
const [sentMessages, setSentMessages] = useState([])
useEffect(() => {
if (fetcher.state === 'submitting') {
const chatMessage = fetcher.formData.get('chatMessage')
setSentMessages([...sentMessages, chatMessage])
}
}, [fetcher.state])
return (
<>
{/* ... */}
<fetcher.Form method="post">
<input
type="text"
name="chatMessage"
placeholder="Enter your message"
/>
<button type="submit">Send</button>
</fetcher.Form>
{/* ... */}
</>
)
}