推送器在提交一次时发送了两次消息。

huangapple go评论98阅读模式
英文:

pusher sends message twice when submitted once

问题

pusher在提交时发送了两次消息。我没有看到任何重复调用的函数,但这仍然发生了。

我使用的是React v18.1.0
我使用的是Golang 1.18

以下是我的React前端代码:

import React, { useState, useEffect } from "react";
import Pusher from "pusher-js";

function App() {
  const [username, setUsername] = useState('username');
  const [messages, setMessages] = useState([]);
  const [message, setMessage] = useState('');
  let allMessages = [];

  useEffect(() => {
      Pusher.logToConsole = true;

      const pusher = new Pusher('-', {
          cluster: '-'
      });

      const channel = pusher.subscribe('chat');
      channel.bind('message', function (data) {
          allMessages.push(data);
          setMessages(allMessages);
      });
  }, []);

  const submit = async e => {
      e.preventDefault();

      await fetch('http://localhost:8000/api/messages', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
              username,
              message
          })
      });

      setMessage('');
  }

  return (
      <div className="container">
          <div className="d-flex flex-column align-items-stretch flex-shrink-0 bg-white">
              <div
                  className="d-flex align-items-center flex-shrink-0 p-3 link-dark text-decoration-none border-bottom">
                  <input className="fs-5 fw-semibold" value={username}
                         onChange={e => setUsername(e.target.value)}/>
              </div>
              <div className="list-group list-group-flush border-bottom scrollarea">
                  {messages.map(message => {
                      return (
                          <div className="list-group-item list-group-item-action py-3 lh-tight">
                              <div className="d-flex w-100 align-items-center justify-content-between">
                                  <strong className="mb-1">{message.username}</strong>
                              </div>
                              <div className="col-10 mb-1 small">{message.message}</div>
                          </div>
                      )
                  })}
              </div>
          </div>
          <form onSubmit={e => submit(e)}>
              <input className="form-control" placeholder="Write a message" value={message}
                     onChange={e => setMessage(e.target.value)}
              />
          </form>
      </div>
  );
}

export default App;

这是我的Golang后端代码:

package main

import (
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/pusher/pusher-http-go"
)

func main() {
	app := fiber.New()

	app.Use(cors.New())

	pusherClient := pusher.Client{
		AppID:   "1421095",
		Key:     "-",
		Secret:  "-",
		Cluster: "ap2",
		Secure:  true,
	}

	app.Post("/api/messages", func(c *fiber.Ctx) error {
		var data map[string]string

		if err := c.BodyParser(&data); err != nil {
			return err
		}

		pusherClient.Trigger("chat", "message", data)

		return c.JSON([]string{})

	})

	app.Listen(":8000")
}

我在网上搜索了很多,但是没有找到解决方案。以上是我编写的所有代码。

英文:

pusher is sending message two times on submit. i dont see any function being repeated or called two times but this still happens

i am using React v18.1.0
i am using Golang 1.18

import React, { useState, useEffect } from &quot;react&quot;;
import Pusher from &quot;pusher-js&quot;;
function App() {
const [username, setUsername] = useState(&#39;username&#39;);
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState(&#39;&#39;);
let allMessages = [];
useEffect(() =&gt; {
Pusher.logToConsole = true;
const pusher = new Pusher(&#39;-&#39;, {
cluster: &#39;-&#39;
});
const channel = pusher.subscribe(&#39;chat&#39;);
channel.bind(&#39;message&#39;, function (data) {
allMessages.push(data);
setMessages(allMessages);
});
}, []);
const submit = async e =&gt; {
e.preventDefault();
await fetch(&#39;http://localhost:8000/api/messages&#39;, {
method: &#39;POST&#39;,
headers: {&#39;Content-Type&#39;: &#39;application/json&#39;},
body: JSON.stringify({
username,
message
})
});
setMessage(&#39;&#39;);
}
return (
&lt;div className=&quot;container&quot;&gt;
&lt;div className=&quot;d-flex flex-column align-items-stretch flex-shrink-0 bg-white&quot;&gt;
&lt;div
className=&quot;d-flex align-items-center flex-shrink-0 p-3 link-dark text-decoration-none border-bottom&quot;&gt;
&lt;input className=&quot;fs-5 fw-semibold&quot; value={username}
onChange={e =&gt; setUsername(e.target.value)}/&gt;
&lt;/div&gt;
&lt;div className=&quot;list-group list-group-flush border-bottom scrollarea&quot;&gt;
{messages.map(message =&gt; {
return (
&lt;div className=&quot;list-group-item list-group-item-action py-3 lh-tight&quot;&gt;
&lt;div className=&quot;d-flex w-100 align-items-center justify-content-between&quot;&gt;
&lt;strong className=&quot;mb-1&quot;&gt;{message.username}&lt;/strong&gt;
&lt;/div&gt;
&lt;div className=&quot;col-10 mb-1 small&quot;&gt;{message.message}&lt;/div&gt;
&lt;/div&gt;
)
})}
&lt;/div&gt;
&lt;/div&gt;
&lt;form onSubmit={e =&gt; submit(e)}&gt;
&lt;input className=&quot;form-control&quot; placeholder=&quot;Write a message&quot; value={message}
onChange={e =&gt; setMessage(e.target.value)}
/&gt;
&lt;/form&gt;
&lt;/div&gt;
);
}
export default App;

this is my backend code in Golang

package main
import (
&quot;github.com/gofiber/fiber/v2&quot;
&quot;github.com/gofiber/fiber/v2/middleware/cors&quot;
&quot;github.com/pusher/pusher-http-go&quot;
)
func main() {
app := fiber.New()
app.Use(cors.New())
pusherClient := pusher.Client{
AppID:   &quot;1421095&quot;,
Key:     &quot;-&quot;,
Secret:  &quot;-&quot;,
Cluster: &quot;ap2&quot;,
Secure:  true,
}
app.Post(&quot;/api/messages&quot;, func(c *fiber.Ctx) error {
var data map[string]string
if err := c.BodyParser(&amp;data); err != nil {
return err
}
pusherClient.Trigger(&quot;chat&quot;, &quot;message&quot;, data)
return c.JSON([]string{})
})
app.Listen(&quot;:8000&quot;)
}

ive searched alot online but i can really find a solution.
above is all the code ive written to create the app

答案1

得分: 0

好的,以下是翻译好的内容:

好的,我知道了。我在index.js中将我的App.js包裹在React Strict Mode中。这导致我的页面渲染了两次,因此useEffect函数运行了两次。所以如果有人遇到这个问题,请确保不要使用React Strict Mode。

英文:

OK I got it. I had my App.js wrapped in React Strict Mode in index.js. It was causing my Page to render 2 times this the useEffect function was running two times. So if anyone is having this issue, make sure you are not using React Strict Mode

huangapple
  • 本文由 发表于 2022年6月9日 22:33:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/72562168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定