首页 > 解决方案 > ReactJS 中的 WebSocket 使用空数组设置状态

问题描述

在此先感谢您的任何建议。我在这里在 ReactJS 中实现 websocket,我的目标是用即将到来的“onmessage”事件填充我的历史状态。对我来说奇怪的是,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 请求。

再次感谢,费利佩。

标签: reactjswebsocketreact-hooks

解决方案


您可以简单地setHistory([...history, {text: e.data}])使用以下代码进行更改setHistory(history=> [...history, {text: e.data}])


推荐阅读