【发布时间】:2023-03-27 10:05:01
【问题描述】:
在此先感谢您的任何建议。 我在这里在 ReactJS 中实现 websocket,我的目标是用即将到来的“onmessage”事件填充我的 history 状态。对我来说奇怪的是,setHistory 在收到来自“websocket.onmessage”事件的消息后正在清空我的数组。它甚至消除了我的初始状态。简化版如下:
function NotificationWebSocket ({object_id}) {
const [history, setHistory] = useState([{text: "The first notification"}]) //
function connectToWebSocket() {
const wsStart = (window.location.protocol === "https:" ? "wss://" : "ws://")
const url = 'localhost:8000/live/'
let socket = new ReconnectingWebSocket(wsStart + url + object_id)
socket.onmessage = e => {
console.log(e.data) // logs the received data correctly
setHistory([...history, {text: e.data}]) // ?? this is setting my history state array to null... ??
setHistory(history.append({text: e.data})) //also cleans my history array here.
}
}
useEffect(() => {
connectToWebSocket()
},[]) // so that we only connect to the websocket once
return (
<div>
We are on a live connection to the server.
{history.map(item=> <div>{item.text}</div>)}
</div>
)
}
注意事项: 我正在使用 ReconnectingWebSocket 库,尽管我尝试不使用它并且发生了同样的事情。 我的 connectToWebSocket 是从 useEffect 内部触发的,否则我会在服务器中收到几个 websockets 请求。
再次感谢, 费利佩。
【问题讨论】:
标签: reactjs websocket react-hooks