所以我有 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
来为其分配值。
我遇到了新的mobx-utils
fromPromise
,我认为author
如果它存在于本地存储中,它会获得该值,并等待AsyncStorage
将其分配给author
可观察对象,因此可以从另一个存储中调用它而不是null
.
我尝试在 中使用fromPromise
firstAuthorStore
来记录author
值,但它undefined
在控制台中显示为 Got ,并且在涉及该部分时通常null
出现错误。BookStore
AuthorStore.author
更新:
class AuthorStore {
@observable author = null;
@computed get theAuthor() {
authorPromise = fromPromise(AsyncStorage.getItem('author').then(data => JSON.parse(data)));
// combine with when..
when(
() => authorPromise.state !== "pending",
() => {
console.log("Got Author", authorPromise.reason || authorPromise.value) // This runs, and returns author
console.log("Got Name", authorPromise.reason || authorPromise.value.name) // This runs, and returns name
return authorPromise.value; // This doesn't get returned in BookStore when calling this computed
}
);
}
}
class BookStore {
@observable book = {
authorName: AuthorStore.theAuthor.name, // doesn't get computed returned value from promise
bookTitle: null
}
}
如何获取计算函数fromPromise
分配的值以将承诺的值返回到under ?AuthorStore
theAuthor
authorPromise
BookStore
authorName