3

所以我有 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来为其分配值。

如何获取AuthorStore构造函数分配给author的值BookStore

4

1 回答 1

2

您可以存储对getItem('author')-promise 的引用,并确保在您在书店中执行任何操作之前完成它:

// authorStore.js
class AuthorStore {
  @observable author = null;
  getAuthorPromise = null;

  constructor() {
    this.getAuthorPromise = AsyncStorage.getItem('author').then(action((data) => {
      this.author = JSON.parse(data);
    }));
  }
}

export default new AuthorStore();

// bookStore.js
class BookStore {
  @observable book = null;

  constructor() {
    authorStore.getAuthorPromise.then(action(() => 
      this.book = {
        authorName: authorStore.author.name,
        bookTitle: null
      };
    ));
  }
}

您还可以在创建任何商店之前获取作者并将作者提供给AuthorStore构造函数,以便您可以BookStore同步创建:

// AuthorStore.js
class AuthorStore {
  @observable author = null;

  constructor(author) {
    this.author = author;
  }
}

export default AuthorStore;

// BookStore.js
class BookStore {
  @observable book = null;
  authorStore = null;

  constructor(authorStore) {
    this.authorStore = authorStore;
    this.book = {
      authorName: authorStore.author.name,
      bookTitle: null
    };
  }
}

export default BookStore;

// app.js
import AuthorStore from './AuthorStore';
import BookStore from './BookStore';

AsyncStorage.getItem('author').then(data => {
  const author = JSON.parse(data);
  const authorStore = new AuthorStore(author);
  const bookStore = new BookStore(authorStore);
}));

请记住,有很多方法可以做到这一点。

于 2016-08-22T18:04:40.843 回答