React Native:始终运行的组件 [英] React native: Always running component

查看:39
本文介绍了React Native:始终运行的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上我不知道如何命名这个问题!

I don't know actually, how to name this question!

我在 React Native 中有一个 JS 文件,它从服务器获取数据并将其与本地数据库进行比较.我需要它同时运行,我怎样才能做到这一点?当应用启动时,它应该运行,更改视图(导航到其他组件)不应破坏它,它应该仍在运行.

I've a JS file in react native that fetches data from server and compares it to local database. i need this to run simultaneously, how can i achieve that? when app starts, that should run, changing views (navigation to other components) should not destroy it, it should still be running.

有什么解决办法吗?

推荐答案

您正在解释一种称为以下内容的设计模式:单身.

You are explaining a design pattern of something called: Singleton.

方法如下:

let instance = null;

class Singleton{  
    constructor() {
        if(!instance){
              instance = this;
        }

        // to test whether we have singleton or not
        this.time = new Date()

        return instance;
      }
}

测试单例在上面的类中,我们定义了一个时间属性来确保我们的单例工作正常.

Testing singleton On above class we have defined a time property to make sure we have singleton working properly.

 let singleton = new Singleton()
 console.log(singleton.time);

 setTimeout(function(){
   let singleton = new Singleton();
   console.log(singleton.time);
 },4000);

如果它为两个实例打印相同的时间,则意味着我们有一个可以工作的单例.

If it prints the same time for both the instances, it means we have a working singleton.

现在,您可以在单例中异步加载您的服务器数据,并使用它做任何您想做的事情.任何时候您尝试访问单例类时,它都会是同一个实例,并且不会被多次实例化.换句话说,它不会被销毁.

Now, you can load your server data asynchronously inside the singleton and do whatever you'd like to do with it. Anytime you try to access the singleton class, it will be the same instance and it will not be instantiated more than once. In other words, it will not be destroyed.

来源:http://amanvirk.me/singleton-classes-in-es6/

这篇关于React Native:始终运行的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆