0

我在我的应用程序中使用不同类型的“Todo”模型。这些类型是通过一个名为“type”的字段实现的。

const BaseTodo = types
  .model("BaseTodo", {
    id: types.optional(types.number, () => Math.random()),
    title: types.string,
    finished: false,
    type: types.string
  })
  .actions(self => ({
    toggle() {
      self.finished = !self.finished;
    },
    changeToShoppingType() {
      const snap = getSnapshot(self);
      console.log("snapshot: ", snap);
      const newSnap = {};
      Object.assign(newSnap, snap, { type: "shopping" });

      console.log("newSnap: ", newSnap);
      applySnapshot(self, newSnap);
      console.log("after apply snap: ", self);
    }
  }));

const ShoppingTodo = BaseTodo.named("ShoppingTodo").props({
  type: types.literal("shopping")
});

const CleaningTodo = BaseTodo.named("CleaningTodo").props({
  type: types.literal("cleaning")
});

export const Todo = types.union(ShoppingTodo, CleaningTodo);

export const TodoStore = types
  .model("TodoStore", {
    todos: types.array(Todo)
  });

我的问题:当我想通过对我的对象应用快照将我的步骤类型从“清洁”更改为“购物”时,我收到错误消息:

...在路径“/type”值“shopping”不可分配给类型:“cleaning”

任何提示如何实现我的用例?

我创建了一个代码框示例,说明我想如何更改类型(只需单击按钮): https ://dm71z.csb.app/

不幸的是,我无法在控制台中显示错误。

4

1 回答 1

1

我认为不可能直接更改孩子的类型,因为您本质上需要一个新的模型实例,因此 todos 数组也必须更新其引用。

所以,你需要做的是让 TodoStore 替换 todo:

export const TodoStore = types
  .model("TodoStore", {
    todos: types.array(Todo),
  })
  .actions(self => ({
    changeToShoppingType: (todo) => {
      const snap = getSnapshot(todo);
      console.log("snapshot: ", snap);
      const newSnap = {};
      Object.assign(newSnap, snap, { type: "shopping" });

      console.log("newSnap: ", newSnap);
      self.todos.splice(self.todos.indexOf(todo), 1, newSnap);
    }
  }));

检查此示例https://codesandbox.io/s/simple-mobx-todolist-m8bre?fontsize=14

于 2019-11-02T20:12:19.867 回答