如果我对消息进行硬编码并发布该方法,则在我的 handleSubmit 方法中按预期工作。但是,如果我用输入状态替换“hello stomp”或使用任何输入提交,我会得到 Uncaught TypeError: Cannot read property 'publish' of undefined” 任何见解将不胜感激
export const Comms = () => {
const [messages, setMessages] = useState();
const [input, setInput] = useState("");
const client = new Client();
client.configure({
brokerURL: "ws://localhost:2019/socket",
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
onConnect: function () {
client.subscribe("/topic/messages", function (msg) {
console.log("WS-MESSAGE: ", msg.body);
});
},
});
const handleSubmit = (event) => {
client.publish({ destination: "/topic/messages", body: "Hello stomp" });
event.preventDefault();
};
useEffect(() => {
client.activate();
}, []);
return (
<div className="comms-cont">
<h1 className="comms-header">Messaging</h1>
<form onSubmit={handleSubmit} className="form-1">
<input
className="forminput"
type="text"
name="message"
onChange={(e) => {
setInput(e.target.value);
}}
/>
</form>
</div>
);
};