MobX - 在另一个商店中运行一个商店的构造函数?

时间:2016-08-22 16:40:50

标签: javascript 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值,而不会先运行构造函数来为其赋值。

如何将AuthorStore构造函数分配给author中的BookStore

1 个答案:

答案 0 :(得分:2)

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

// 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);
}));

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