【问题标题】:Cannot read property 'publish' of undefined in react无法在反应中读取未定义的属性“发布”
【发布时间】:2021-09-17 07:18:23
【问题描述】:

在我的 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>
  );
};

【问题讨论】:

    标签: reactjs websocket react-hooks stomp stompjs


    【解决方案1】:

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

    <input
     className="forminput"
     type="text"
     name="message"
     value={input}
     onChange={(e) => {
     setInput(e.target.value);
     }}
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2022-09-27
      • 2021-11-20
      • 2017-01-29
      相关资源
      最近更新 更多