给出MyQuestionStore
商店:
class MyQuestionStore {
@observable asked = 'today';
@observable answered = false;
@observable question = {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
// some more initial state observables...
// some actions below...
}
const myQuestionStore = new MyQuestionStore();
export default myQuestionStore;
将所有商店可观察量重置回初始状态数据的正确方法是什么('今天' / false / 0 / null / etc ..)?
注意:例如MyQuestionStore.reset()
之类的东西,我认为这将是一个很好的MobX方式,但我认为它不存在。我必须编写一个名为reset
的动作,并手动将每个observable重置回其初始状态。我不认为这是正确的方法,因为如果我添加更多observables
,我每次都必须手动将其添加到reset
操作。
答案 0 :(得分:7)
编辑:这是一个老答案,在较新版本的mobx中不起作用。
如果使用reset()
初始化对象,则可以避免重复代码。这就是我的意思:
import { extendObservable } from "mobx";
class MyQuestionStore {
constructor() {
this.reset();
}
@action reset() {
extendObservable(this, {
asked: 'today',
answered: false,
question: {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
});
}
}
答案 1 :(得分:3)
我最终不得不在重置函数中重复默认的observable,所以它看起来像这样:
class MyQuestionStore {
@observable asked = 'today';
@observable answered = false;
@observable question = {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
@action reset = () => {
this.asked = 'today';
this.answered = false;
this.question = {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
}
}
const myQuestionStore = new MyQuestionStore();
export default myQuestionStore;
我仍然觉得有一种比重复它并保持干爽更好的方法。我现在将问题保持开放,希望有更好的DRY答案。
答案 2 :(得分:3)
如果您不需要深度重置,createViewModel
中的mobx-utils
实用程序可能会派上用场:https://github.com/mobxjs/mobx-utils/#createviewmodel
答案 3 :(得分:1)
要重置存储,您可以执行以下操作:
const initialValue = {
name: 'John Doe',
age: 19,
}
@action reset() {
Object.keys(initialState).forEach(key => this[key] = initialState[key]);
}
您可以设置初始存储值:
class myStore {
constructor() {
extendObservable(this, initialState);
}
}
答案 4 :(得分:0)
为什么不采用以下方法
class MyQuestionStore {
@observable asked;
@observable answered;
@observable question;
constructor() {
super()
this.init()
}
@action reset() {
this.init()
}
@action init() {
this.asked = 'today';
this.answered = false;
this.question = {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
}
// some more initial state observables...
// some actions below...
}
const myQuestionStore = new MyQuestionStore();
export default myQuestionStore;