[求助] React WebSocket Stomp 后端返回不能实时显示

2020-09-07 17:32:00 +08:00
 qwertty01

单独调用 addLog 是可以实时显示的 但是调用 connect 和 sendMessage 时,不能实时显示必须点击一下才能显示出来 能不能用 useEffect ?

export const WebSocketPage = () => {
    const [log, setLog] = useState([])
    const [stompClient, setStompClient] = useState(null)


    const connect = () => {
        const socket = new SockJS(WEB_SOCKET_URL)
        const stompClient = Stomp.over(socket)
        stompClient.connect({}, function (frame) {
            setStompClient(stompClient)
            addLog(frame)
            stompClient.subscribe("/topic/greeting", function (greeting) {
                addLog(JSON.parse(greeting.body).content)
            })
        })
    }

    const sendMessage = () => {
        if (stompClient !== null) {
            stompClient.send("/app/hello", {}, JSON.stringify({"name": "Hello World!"}))
            addLog("send message: /app/hello", JSON.stringify({"name": "Hello World"}))
        }
    }

    const addLog = (message) => {
        setLog(prevState => {
            let current = prevState;
            console.log(current)
            current.push(message.toString())
            return current
        })
    }


    return (
        <div>
            
                <Button value="connection" onClick={connect} label="Connect"/>
                <Button label="Send Message" onClick={sendMessage}/>
                <Button label="Add Log" onClick={() => addLog(1)}/>
                    <pre>
                        {log.map((value, index) => <div key={index}>{value}</div>)}
                    </pre>
        </div>
    );
}
743 次点击
所在节点    问与答
1 条回复
qwertty01
2020-09-07 19:23:55 +08:00
在线等。。。急。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/704926

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX