所以我有两家商店,一家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是null一样。因此,它从author中读取默认的AuthorStore值,而不需要先运行构造函数来为其分配值。
我偶然发现了新的mobx-utils fromPromise,如果它存在于本地存储中,它将得到author值,然后等待AsyncStorage将其分配给可观察到的author,这样就可以从另一个商店调用它,而不是null。
我尝试首先在AuthorStore中使用AuthorStore记录author值,但它显示为控制台中的Got undefined,以及在AuthorStore.author部分时BookStore中常见的null错误。
更新:
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计算函数theAuthor分配的authorPromise值,以便将承诺的authorPromise值返回到authorName下的BookStore中
发布于 2016-08-23 15:18:25
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
}
}https://stackoverflow.com/questions/39103568
复制相似问题