[MST] Store Store in Local Storage

本文介绍如何使用 onSnapshot 监听状态变化,并将状态快照存储到本地存储中,确保即使在离线状态下也能提供良好的用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

For an optimal user and developer experience, storing state in local storage is often a must.

In this lesson you will learn:

  • Using onSnapshot to get notified about new snapshots
  • Storing snapshots in local storage
  • Restore a state tree from local storage
  • Verifying whether a snapshot conforms to a model using Model.is(...)

 

let initialState = {
    items: [
        {
            name: "LEGO Mindstorms EV3",
            price: 349.95,
            image: "https://images-na.ssl-images-amazon.com/images/I/71CpQw%2BufNL._SL1000_.jpg"
        },
        {
            name: "Miracles - C.S. Lewis",
            price: 12.91,
            image:
                "https://images-na.ssl-images-amazon.com/images/I/51a7xaMpneL._SX329_BO1,204,203,200_.jpg"
        }
    ]
}

if (localStorage.getItem("wishlistapp")) {
    const json = JSON.parse(localStorage.getItem("wishlistapp"))
    if (WishList.is(json)) initialState = json // check whether the structure is changed or not
}

const wishList = WishList.create(initialState)

// if the snapshot changed, add to the localstorage onSnapshot(wishList, snapshot
=> { localStorage.setItem("wishlistapp", JSON.stringify(snapshot)) })

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值