laravel 广播 - 客户端多次收到一个响应

laravel broadcasting - client receives one response several times

我正在创建一个简单的实时聊天应用程序 (laravel, reactjs,pusher)。

服务器只是从客户端 (ReactJs) 获取 name AND text message,将数据存储在数据库中,然后将新数据传递给我的事件,事件将其传递给客户端。

它有效,但我的问题是客户端中的侦听器多次接收数据,并且每次请求后接收数据的计数都会增加。
我只想从服务器获取一次数据。

我的控制器:

class MessageController extends Controller
{
    public function index(Request $request){
       $message = Message::create([
        'name' => $request->name,
        'text' => $request->text
      ])->toArray();

     return event(new MessageEvent($message));
    }
}

我的活动:

class MessageEvent implements ShouldBroadcast
{
  use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public $data;
    public function __construct($message)
    {
        $this->data = $message;

    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn(){
       return 'messages';
    }

    public function broadcastAs(){
        return 'MessageEvent';
    }

    public function broadcastWith(){
    return  [
        'id' => $this->data['_id'],
        'name' => $this->data['name'],
        'text' => $this->data['text']
      ];
    }
}

我的客户端聊天室:

export function ChatPage({ dispatch, getMessages, sendMessage, chatPage }) {
  useInjectReducer({ key: 'chatPage', reducer });
  useInjectSaga({ key: 'chatPage', saga });
  const [text, setText] = useState('');

  window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '8171e9879fae800e8fef',
    cluster: 'ap2',
    forceTLS: true,
  });

  const channel = window.Echo.channel('messages');
  channel.listen('.MessageEvent', function(data) {
    console.log(data, 'index');
  });

  return (
    <ChatWrapper>
      <Helmet>
        <title>ChatPage</title>
        <meta name="description" content="Description of ChatPage" />
      </Helmet>
      <div className="container">
        {chatPage.data
          ? chatPage.data.map(item => (
              <div
                className={
                  item.name === localStorage.getItem('chat')
                    ? 'item-rigth'
                    : 'item-left'
                }
                key={item.id}
              >
                <span>
                  {item.name}
                  <hr />
                  {item.text}
                </span>
              </div>
            ))
          : null}
        <div className="form">
          <div>
            <input
              type="text"
              value={text}
              onChange={e => setText(e.target.value)}
              placeholder="Type Something..."
            />
            <img
              src={Send}
              onClick={() => {
                sendMessage(text);
                setText('');
              }}
            />
          </div>
        </div>
      </div>
    </ChatWrapper>
  );
}

ChatPage.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  chatPage: makeSelectChatPage(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    sendMessage: text => dispatch(messageAction(text)),
    getMessages: data => dispatch(messageSuccessAction(data)),
  };
}

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

export default compose(
  withConnect,
  memo,
)(ChatPage);

我认为当我从邮递员调用事件时它工作正常但是当我从我的客户端请求服务器时它给出了几次响应(我认为这是为了重新呈现页面)。

我应该怎么做?

嘿,我解决了问题:)。

我把我的听众部分放到 useEffect:

  useEffect(() => {
    window.Echo = new Echo({
      broadcaster: 'pusher',
      key: '8171e9879fae800e8fef',
      cluster: 'ap2',
      forceTLS: true,
    });
    const channel = window.Echo.channel('messages');
    channel.listen('.MessageEvent', function(data) {
      console.log(data, 'data');
    });
  }, []);