MobX - 使用fromPromise在商店构造函数中承诺的可观察值在另一个商店中访问时保持为null?

时间:2016-08-23 14:09:47

标签: mobx

所以我有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 BookStoreauthorName }?

1 个答案:

答案 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
  }
}