[MST] Describe Your Application Domain Using mobx-state-tree(MST) Models

In this lesson, we introduce the running example of this course, a wishlist app. We will take a look at the core of mobx-state-tree (MST), models. Models describe the shape of your state and perform type validation.

You will learn:

  • Defining models using types.Model
  • Instantiating models from JSON using Model.create
  • Primitive types: types.string & types.number
  • Type inference for primitive types
  • types.array
  • types.optional
  • Composing models into a model tree
  • Testing models using jest

 

To create a model:

import { types } from "mobx-state-tree"

export const WishListItem = types.model({
    name: types.string,
    price: types.number,
    image: ""
})

export const WishList = types.model({
    items: types.optional(types.array(WishListItem), [])
})

'types' is similar to React PropTypes.

 

Once model is created, then we can write tests to verify:

import { WishList, WishListItem } from "./WishList"

it("can create a instance of a model", () => {
    const item = WishListItem.create({
        name: "Chronicles of Narnia Box Set - C.S. Lewis",
        price: 28.73
    })

    expect(item.price).toBe(28.73)
    expect(item.image).toBe("")
})

it("can create a wishlist", () => {
    const list = WishList.create({
        items: [
            {
                name: "Chronicles of Narnia Box Set - C.S. Lewis",
                price: 28.73
            }
        ]
    })

    expect(list.items.length).toBe(1)
    expect(list.items[0].price).toBe(28.73)
})

 

转载于:https://www.cnblogs.com/Answer1215/p/8337570.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值