您可以存储对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);
}));
请记住,有很多方法可以做到这一点。