所以我有2个商店,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
为空。因此,它会从author
读取默认的AuthorStore
值,而不会先运行构造函数来为其赋值。
如何将AuthorStore
构造函数分配给author
中的BookStore
?
答案 0 :(得分:2)
您可以存储对getItem('author')
- 承诺的引用,并确保在您在书店中执行任何操作之前完成它:
// 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);
}));
请记住,有很多方法可以做到。