我刚接触react Native.我希望将多个小字符串存储到通用单例对象类中,并希望从所有组件的单例对象中访问它。有没有人能帮我实现react native的单例对象?
例如
组件1 --登录按钮-- >>成功-->需要将userID存储到单例对象中。
组件2 -->从单例对象获取存储的userID。我怎样才能实现它。
发布于 2017-07-04 13:28:41
这里有一个简单的方法……
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;
}
}
下面是如何使用它。
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);
希望这对你有用:)
发布于 2017-06-29 04:38:19
我建议使用AsyncStorage创建一个存储数据的静态类。您在评论中提到,您已经在使用AsyncStorage
,但不喜欢将此功能传播到您的应用程序中。(例如,到处都是try-catches
,每个组件需要检查密钥是否可用,等等)如果这个功能在一个类中,它会清理你的代码很多。
这种方法的另一个好处是,您可以很容易地交换出实现,例如,您可以选择使用内存中的对象或AsyncStorage
或其他任何东西,您只需更改这一个文件
注意: AsyncStorage
is not a security to store敏感信息。有关AsyncStorage
和替代方案的安全性的详细信息,请参阅this question。
这就是说,这就是我想象的全局数据持有者类的样子:
export default class dataManager {
static storeKeyValue(key, value) {
// your choice of implementation:
// check if key is used
// wrap in try-catch
// etc.
}
static getValueForKey(key) {
// get the value out for the given key
}
// etc...
}
然后,要在应用程序中的任何位置使用这个类,只需在需要的地方导入,如下所示:
import dataManager from 'path/to/dataManager.js';
// store value
dataManager.storeKeyValue('myKey', 'myValue');
// get value
const storedValue = dataManager.getValueForKey('myKey');
编辑:在大多数情况下,使用Flux、Redux或类似技术的可能是首选/建议的方式,但如果你觉得单例模式最适合你的应用,那么这是一个很好的方式。请参阅
发布于 2017-06-23 19:11:34
有一个解决办法,react native packager require
编译阶段的所有模块生成一个包,在第一次请求之后,它为模块生成一个内部id,从那时起在整个运行时内存中引用它,所以如果我们从文件中导出一个类的实例,那么每当导入该文件时,该对象都将被引用。
TLDR;
解决方案I:
class abc {
}
module.exports = new abc()
解决方案II :我假设您想要获取静态且不会更改的字符串,因此您可以将它们声明为静态,并使用类名直接访问它们
仅供参考:这也适用于webpack。
https://stackoverflow.com/questions/44719103
复制相似问题