我是react native编码方面的新手,但对objective-c和swift编码有经验,希望在react native中使用单例模式.

var Singleton = (function () {
    var instance;

    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

function run() {

    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();

    alert("Same instance? " + (instance1 === instance2));  
}

正如我们在上面的代码中看到的,我们正在创建单例函数而不是类.

推荐答案

这是我对singleton类的实现...

控制器.js

export default class Controller {
    static instance = Controller.instance || new Controller()

    helloWorld() {
        console.log("Hello World... \(^_^)/ !!")
    }
}

用法:

import Controller from '控制器.js'

Controller.instance.helloWorld()

React-native相关问答推荐

Reaction-Native-pdf文件不是PDF格式或已损坏

ReactNative如何在填充编辑表单 timeshift 除按钮禁用状态

React Native 映射未定义不是函数

React Native 在升级到 0.56 版本后崩溃

React Native 上传到 S3 存储空间

react-native: 'adb' 不是内部或外部命令、可运行程序或批处理文件

纯在 Swift 中的 React Native 应用程序

ReactNative FlatList 一次渲染所有元素?

Test suite无法运行 TypeError:Cannot read property ‘default’ of undefined

如何在 react-native 上自动聚焦下一个 TextInput

没有找到 `React-fishhook` 的 podspec

React Native:自定义字体在 Android 和 iOS 上呈现不同

react-native如何禁用android开发模式

如何在 React Native 中重复图案图像以创建背景?

使用 React Navigation 导航堆栈时重新渲染组件

Tools > Android 菜单在 Android Studio 中不存在

将 setState 与 promise 一起使用后出现错误

Android Log

是否可以将 Material UI 库与 React Native 一起使用?

react-native iOS 应用在部署后不显示静态/本地资源