gpt4 book ai didi

javascript - 为什么 Gun.js 在 ReactJs 中重复消息

转载 作者:行者123 更新时间:2023-12-05 04:28:04 24 4
gpt4 key购买 nike

我正在 React 应用程序中实现 gun.js。但是消息在每次渲染和每次更新时都是重复的。有人可以帮助找出我的代码有什么问题吗。

这是我的代码。

import Gun from "gun/gun";
import { IGunChain, IGunInstance } from "gun/types";

class GunService {
public gun: IGunInstance<any> | undefined;
public messageListener:
| IGunChain<any, IGunInstance<any>, IGunInstance<any>, "messages">
| undefined;

constructor() {
this.gun = Gun("http://localhost:4000" + "/gun");
this.messageListener = this.gun.get("messages");
}

public sendMessage(message: any) {
this.messageListener?.set(message);
}
}
export const gunServices = new GunService();

然后在我的组件中:获取有关每个新更新的消息

   useEffect(() => {
gunServices.messageListener?.map().on((message) => {
setMessages((prevMessage) => [...prevMessage, message]);
});
}, []);

发送消息函数

      const onSendMessage = () => {

const message = {
senderUsername: "John Doe",
senderId: "Doe---id",
receiverUsername: "John Doe",
receiverId: "zizou_id",
message: messageValue,
date: Date.now().toLocaleString(),
time: Date.now().toLocaleString(),
};

gunServices.sendMessage(message);
setMessageValue("");
};

最佳答案

我对此的简单修复是添加 useRef()

   import { useState, useRef, useEffect } from "react"; 

useEffect(() => {
if (loaded.current !== false) return; // Added

gunServices.messageListener?.map().once().on((message) => {
setMessages((prevMessage) => [...prevMessage, message]);

loaded.current = true; // Added
});
}, []);

关于javascript - 为什么 Gun.js 在 ReactJs 中重复消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72676941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com