ReactJS和Singleton问题随着更新

发布于 2025-01-30 21:16:25 字数 589 浏览 1 评论 0原文

首先,我知道在React App中共享此类数据不是很好的做法, 但是 - 说“我别无选择” 现在,我在ReactJ中与Singleton有一个问题。 我可以看到,如果我试图获得Singleton的实例 - 构造函数只能工作一次。 在构造函数内部,我对Web插座有订阅,该Web插座更新了Singleton内部的数据。 但是,然后我尝试从应用程序中的不同位置(不更新)传达数据显示我的版本,然后我进行了实例。我该如何解决?

export default class Manager {
    constructor(){
        this.data = null;
        socket.on('event', this.parseData)
    }

    static getInstance(){
       if (!this.instance) {
         this.instance = new QuotasManager();
       }
      return this.instance;
    }
   
   parseData(data){ ///parsedata}
   
   getData(){ return this.data}

}

Firstable, I know its not good practice to share data like this in react App,
But - let say "I have no choice"
Now I have an issue with singleton in ReactJs.
I can see that if i trying to get instance of singleton - constructor works only once.
Inside constructor I have subscription to web socket which updates data inside singleton.
But then Im try to reach the data from different places in app - its not update - shows me version then I took instance. How can I solve it?

export default class Manager {
    constructor(){
        this.data = null;
        socket.on('event', this.parseData)
    }

    static getInstance(){
       if (!this.instance) {
         this.instance = new QuotasManager();
       }
      return this.instance;
    }
   
   parseData(data){ ///parsedata}
   
   getData(){ return this.data}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缘字诀 2025-02-06 21:16:25

抱歉,我发现这是我的错。我松开范围,然后使用插座事件上的回调。只需忘记添加箭头函数以获取我的

Sorry for disturb - I found that its my fault. I loose my scope then use callback on socket event. Just forgot to add arrow function to got my this

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文