React native:始终运行的组件

React native: Always running component

本文关键字:运行 组件 native React      更新时间:2023-09-26

我其实不知道该如何命名这个问题!

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

解决方案吗?

你在解释一种叫做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;
      }
}

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

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

如果两个实例输出相同的时间,就意味着我们有一个工作的单例。

现在,您可以在单例中异步加载服务器数据,并对其进行任何操作。当你试图访问单例类时,它将是同一个实例,并且不会被实例化多次。换句话说,它不会被破坏。

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

我迟到了,但这可能会帮助别人,

一个选择是创建一个单例类。但另一种选择是为导航文件创建一个容器。比;导航容器只是一个普通的组件,其子组件是主组件导航组件。

你在导航容器中的代码一直在运行。

我使用这样的导航容器…

     export default function App() {
        return (
            <Provider store={store}>
                    <NavigationContainer />
            </Provider>
           );
         }

从这个导航容器返回导航组件,比如>这个

    return (
 <AuthNavigator ref={navRef} />
    );