0

如果我对消息进行硬编码并发布该方法,则在我的 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>
  );
};

4

1 回答 1

0

您想使用受控输入组件。像这样将 prop 值添加到输入中:

<input
 className="forminput"
 type="text"
 name="message"
 value={input}
 onChange={(e) => {
 setInput(e.target.value);
 }}
/>
于 2021-07-09T05:17:13.520 回答