4

所以我有 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.

我尝试在 中使用fromPromisefirstAuthorStore来记录author值,但它undefined在控制台中显示为 Got ,并且在涉及该部分时通常null出现错误。BookStoreAuthorStore.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 ?AuthorStoretheAuthorauthorPromiseBookStoreauthorName

4

1 回答 1

4

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
  }
}
于 2016-08-23T15:18:25.250 回答