gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:40:21 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于javascript - MobX - 在另一个商店运行一个商店的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39084658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com