所以我有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
中使用AuthorStore
来记录author
值,但在控制台中显示为[{1}},并且通常undefined
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
分配的AuthorStore
值,以便将承诺的theAuthor
值返回到authorPromise
BookStore
下authorName
}?
答案 0 :(得分:3)
FromPromise创建一个包装原始承诺的新对象。因此,您的authorFromStorage
只是您示例中的正常承诺,根本没有state
属性。因此,您应该将代码更改为:
authorPromise = fromPromise(AsyncStorage.getItem('author').then(data => JSON.parse(data)))
然后when(() => authorPromise.state !== "pending")
等..
**更新**
class AuthorStore {
@observable author = null;
constructor() {
AsyncStorage.getItem('author').then(data => { this.author = JSON.parse(data) });
}
}
class BookStore {
@observable book = {
authorName: function() { // a function in an observable creates a computed prop
return AuthorStore.author && AuthorStore.author.name
},
bookTitle: null
}
}