MobX -运行一个存储的构造函数在另一个

MobX - Run constructor of one store in another?

本文关键字:存储 构造函数 另一个 一个 运行 MobX      更新时间:2023-09-26

所以我有两个商店,一个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的默认值,而没有先运行构造函数为其赋值。

如何获得AuthorStore构造函数在BookStore中分配给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);
}));

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