MobX -运行一个存储的构造函数在另一个
MobX - Run constructor of one store in another?
所以我有两个商店,一个AuthorStore
:
class AuthorStore {
constructor() {
// has author.name and is always present in storage
AsyncStorage.getItem('author').then(action((data) => {
this.author = JSON.parse(data);
}));
}
@observable author = null;
}
和BookStore
:
import AuthorStore from 'authorStore';
class BookStore {
@observable book = {
authorName: AuthorStore.author.name,
bookTitle: null
}
}
我一直在BookStore
中得到一个错误,它不能得到null
的属性,好像AuthorStore.author.name
是空的。因此,它从AuthorStore
中读取author
的默认值,而没有先运行构造函数为其赋值。
如何获得AuthorStore
构造函数在BookStore
中分配给author
的值?
您可以存储对getItem('author')
-promise的引用,并确保在对书店执行任何操作之前实现它:
// authorStore.js
class AuthorStore {
@observable author = null;
getAuthorPromise = null;
constructor() {
this.getAuthorPromise = AsyncStorage.getItem('author').then(action((data) => {
this.author = JSON.parse(data);
}));
}
}
export default new AuthorStore();
// bookStore.js
class BookStore {
@observable book = null;
constructor() {
authorStore.getAuthorPromise.then(action(() =>
this.book = {
authorName: authorStore.author.name,
bookTitle: null
};
));
}
}
您还可以在创建任何存储之前获取作者,并将作者提供给AuthorStore
构造函数,这样您就可以同步创建BookStore
:
// AuthorStore.js
class AuthorStore {
@observable author = null;
constructor(author) {
this.author = author;
}
}
export default AuthorStore;
// BookStore.js
class BookStore {
@observable book = null;
authorStore = null;
constructor(authorStore) {
this.authorStore = authorStore;
this.book = {
authorName: authorStore.author.name,
bookTitle: null
};
}
}
export default BookStore;
// app.js
import AuthorStore from './AuthorStore';
import BookStore from './BookStore';
AsyncStorage.getItem('author').then(data => {
const author = JSON.parse(data);
const authorStore = new AuthorStore(author);
const bookStore = new BookStore(authorStore);
}));
请记住,有很多方法可以做到这一点
相关文章:
- ES6构造函数返回基类的实例
- 使用Google Visualization动态调用构造函数
- javascript中对象构造函数中的var属性与this.properties
- 理解typescript中的构造函数接口
- 为什么构造函数不是构造函数
- 如果在构造函数中有“返回”,则在 JavaScript 中的新运算符中做了什么
- 拦截对构造函数的调用
- 使用闭包共享构造函数参数
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- 从js引擎的角度来看闭包和构造函数是如何工作的
- 如何使用此从对象访问构造函数
- Javascript:为什么是构造函数's __proto__属性Empty(){}
- 当一个重要的构造函数参数丢失时应该发生什么
- Chrome Javascript日期构造函数错误
- 如何使用构造函数's的输出,以便将值插入到对象中
- 为什么在调用父构造函数时在[]中发送数据
- 从构造函数创建一个匿名函数对象,并将其存储在另一个对象中
- 存储 JavaScript 构造函数供以后使用
- MobX -运行一个存储的构造函数在另一个
- 覆盖Ext.data.存储,调用构造函数