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

MobX - Run constructor of one store in another?

所以我有 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 为空一样。所以它从 AuthorStore 中读取默认的 author 值,而无需构造函数 运行 首先为其分配值。

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

您可以存储对 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);
}));

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