10

给定一家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;

将所有 store observables 重置为其初始状态数据('today'/false/0/null/etc..)的正确方法是什么?

注意:例如,我认为这是一种很好的MobXMyQuestionStore.reset()方式,但我认为它不存在。我将不得不编写一个名为reset并手动将每个可观察对象重置回其初始状态的操作。我认为这不是正确的方法,因为如果我添加 more ,我每次observables都必须手动将它们添加到操作中。reset

4

5 回答 5

8

编辑:这是一个旧答案,在较新版本的 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
      }
    });
  }
}
于 2016-09-11T17:54:01.560 回答
4

如果您不需要深度重置,该createViewModel实用程序mobx-utils可能会派上用场:https ://github.com/mobxjs/mobx-utils/#createviewmodel

于 2016-09-06T18:01:20.707 回答
4

我最终不得不在 reset 函数中重复默认的 observables,所以它看起来像这样:

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 答案。

于 2016-09-04T16:56:38.407 回答
3

要重置商店,您可以执行以下操作:

const initialValue = {
  name: 'John Doe',
  age: 19,
}

@action reset() {
  Object.keys(initialState).forEach(key => this[key] = initialState[key]);
}

您可以设置初始存储值:

class myStore {
  constructor() {
    extendObservable(this, initialState);
  }
}
于 2019-01-08T13:13:09.513 回答
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;
于 2019-11-25T15:00:59.677 回答