首页 > 其他 > 详细

[MST] Remove Model Instances from the Tree

时间:2018-01-28 10:57:23      阅读:226      评论:0      收藏:0      [点我收藏+]

In this lesson we will dive a bit more into the tree semantics of MST.

In this lesson you will learn:

  • Actions can only modify their own subtree
  • The use of getParent to find the parent of a model instance
  • Using destroy to remove an instance entirely from the tree

 

The whole point for removing data from model is call ‘destroy‘, sometime you might need ‘getParent‘ if the data you want to remove is not in current tree node.

 

import { types, getParent, destroy } from "mobx-state-tree"

export const WishListItem = types
    .model({
        name: types.string,
        price: types.number,
        image: ""
    })
    .actions(self => ({
        changeName(newName) {
            self.name = newName
        },
        changePrice(newPrice) {
            self.price = newPrice
        },
        changeImage(newImage) {
            self.image = newImage
        },
        remove() {
            getParent(self, 2).remove(self)
        }
    }))

export const WishList = types
    .model({
        items: types.optional(types.array(WishListItem), [])
    })
    .actions(self => ({
        add(item) {
            self.items.push(item)
        },
        remove(item) {
            destroy(item)
        }
    }))
    .views(self => ({
        get totalPrice() {
            return self.items.reduce((sum, entry) => sum + entry.price, 0)
        }
    }))

 

[MST] Remove Model Instances from the Tree

原文:https://www.cnblogs.com/Answer1215/p/8369681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!