V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
qwertty01
V2EX  ›  问与答

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

  •  1
     
  •   qwertty01 · 2020-09-07 17:32:00 +08:00 · 717 次点击
    这是一个创建于 1298 天前的主题,其中的信息可能已经有所发展或是发生改变。

    单独调用 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>
        );
    }
    
    1 条回复    2020-09-07 19:23:55 +08:00
    qwertty01
        1
    qwertty01  
    OP
       2020-09-07 19:23:55 +08:00
    在线等。。。急。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3190 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 13:05 · PVG 21:05 · LAX 06:05 · JFK 09:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.