gpt4 book ai didi

javascript - useState hook 的 set State 函数无法与 socket.io 一起正常工作

转载 作者:行者123 更新时间:2023-12-04 09:36:46 24 4
gpt4 key购买 nike

我有一个使用 React Hooks 和 socketio 的组件:

import React, { useState, useEffect } from "react";
import io from "socket.io-client";

const Live = () => {
const [messages, setMessages] = useState([]);
const ENDPOINT = "localhost:5000";

useEffect(() => {
socket = io(ENDPOINT);
socket.on("message", (message) => {
setMessages((messages) => [message, ...messages]);
//setMessages([message, ...messages]); //It doesn't work
});
}, [ENDPOINT]);

// rest of the code

};

如果我使用 setMessages([message, ...messages]),它不起作用,并且在从套接字接收到新消息时,messages< 中的所有先前消息 数组不见了。这种行为背后的原因是什么?

最佳答案

我不建议在此处使用 useState 来执行您正在执行的操作。相反,请考虑 useReducer

const Live = () => {
const ENDPOINT = "localhost:5000";

const [{ messages }, dispatch] = useReducer((state, action) => {
if (action.type === 'NEW_MESSAGE') {
state.messages.push(action.message)
return state
}
return state
}, { messages: [] })

useEffect(() => {
socket = io(ENDPOINT);
socket.on("message", (message) => {
dispatch({ type: 'NEW_MESSAGE', message })
});
}, [ENDPOINT])

// rest of the code
};

来自 useReducer 上的 React 文档

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

在您的情况下,下一个 messages 状态取决于之前的 messages 状态。

关于javascript - useState hook 的 set State 函数无法与 socket.io 一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62541070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com