我正在构建一个小型聊天应用程序,但我在反应中接收消息时有问题。问题是,当我收到消息IsetMessages
时,但同时messages
状态被清除。问题可能是我不知道在哪里放置socket.on
,目前它在useEffect
钩子内。
export const Room = ({ socket }) => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const { id } = useParams();
useEffect(() => {
socket.emit("join room", id);
}, []);
useEffect(() => {
socket.on("message", (message) => {
setMessages([
...messages,
{ message: message, createdBy: "other", id: uuidv4() },
]);
});
}, []);
const sendMessage = () => {
console.log("send");
socket.emit("message", input);
setMessages([
...messages,
{ message: input, createdBy: "me", id: uuidv4() },
]);
};
console.log("foo");
return (
<div className="flex justify-center text-center">
<div className="w-screen h-screen px-2 max-w-4xl mt-10">
<p className="text-3xl">Code: {id}</p>
<div className="bg-white w-full h-3/4 rounded-xl border-2 border-black overflow-y-auto">
{messages.map((message) => (
<Message
text={message.message}
createdBy={message.createdBy}
key={message.id}
/>
))}
</div>
<div className="flex flex-row border-2 border-black mt-2 rounded-xl p-2 bg-white">
<input
className="flex-grow border-none focus:outline-none"
onInput={(e) => setInput(e.target.value)}
/>
<button
className=" bg-green-500 rounded-xl px-2 py-1"
onClick={sendMessage}
>
Send
</button>
</div>
</div>
</div>
);
};
我很确定你有一个闭包问题。messages
不是你想的那样,当它在useEffect中运行时——它可能不是最新版本。
使用setter的函数变体更安全,也是一个好做法。这样可以确定messages
是当前版本:
setMessages(messages => [
...messages,
{ message: message, createdBy: "other", id: uuidv4() },
]);