反应原生中的单例对象 [英] singleton object in react native

查看:43
本文介绍了反应原生中的单例对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 react native 的新手.我想将多个小字符串存储到常见的单例对象类中,并希望从所有组件的单例对象中访问它.任何人都可以帮助我实现 React Native 的单例对象.

I'm new in react native.I want store multiple small small strings to common singleton object class and want to access it from singleton object for all component. Can anyone help me singleton object implementation for react native.

组件 1 -- 登录按钮 -- >> 成功 --> 需要将用户 ID 存储到单例对象中.

Component 1 -- Login button -- >> success --> need to store userID into singleton object.

组件 2 --> 从单例对象中获取存储的用户 ID.我该如何实施.

Component 2 --> get stored userID from singleton object. How can i implement it.

推荐答案

这里有一个简单的方法...

Here is a simple way of doing it...

export default class CommonDataManager {

    static myInstance = null;

    _userID = "";


    /**
     * @returns {CommonDataManager}
     */
    static getInstance() {
        if (CommonDataManager.myInstance == null) {
            CommonDataManager.myInstance = new CommonDataManager();
        }

        return this.myInstance;
    }

    getUserID() {
        return this._userID;
    }

    setUserID(id) {
        this._userID = id;
    }
}

这里是如何使用它...

And here is how to use it...

import CommonDataManager from './CommonDataManager';


// When storing data.
let commonData = CommonDataManager.getInstance();
commonData.setUserID("User1");


// When retrieving stored data.
let commonData = CommonDataManager.getInstance();
let userId = commonData.getUserID();
console.log(userId);

希望这对你有用:)

这篇关于反应原生中的单例对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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