单独调用 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
qwertty01 OP 在线等。。。急。。。
|