[Javascript] Simplify Creating Immutable Data Trees With Immer
Immer is a tiny library that makes it possible to work with immutable data in JavaScript in a much more straight-forward way by operating on a temporarily draft state and using all the normal JavaScript API's and data structures. The first part of the lesson explains how to use Immer, and the second part of the lesson shows you how it can be used to simplify, for example, Redux reducers.
Immer has a few unique features:
- Supports arbitrary, deep modifications in immutable data trees
- Strongly typed
- Uses JavaScript native data structures, no new API to learn
- Automatically freezes any data that is produced
The whole point of Immer is that you can wrap you reducer function with the function immer provide, let's call 'produce'. When you call it, if you don't do anything, it just return your previous state, if you do any partial mutation, if will keep original object untouched, instead creating immutable version return to you. therefore make code much simpler.
// Before const byId = (state, action) => { switch (action.type) { case RECEIVE_PRODUCTS: return { ...state, ...action.products.reduce((obj, product) => { obj[product.id] = product return obj }, {}) } default: return state } }
// After import produce from 'immer' const byId = (state, action) => produce(state, draft => { switch (action.type) { case RECEIVE_PRODUCTS: action.products.forEach(product => { draft[product.id] = product }) } })
Or an improved version:
import produce from 'immer' const byId = produce((draft, action) => { switch (action.type) { case RECEIVE_PRODUCTS: action.products.forEach(product => { draft[product.id] = product }) } })
相关文章
- javascript 高级教程 视频_精通JavaScript
- 【说站】javascript函数节流实现的两种方式
- JavaScript刷LeetCode拿offer-分治_2023-03-01
- 常用的JavaScript代码块
- JavaScript学习总结(二十)——Javascript非构造函数的继承详解编程语言
- Javascript常用运算符(Operators)-javascript基础教程
- Javascript阻止javascript事件冒泡,获取控件ID值
- JavaScript选中文字并响应获取的实现代码
- Web开发之JavaScript
- Javascript拓展String方法小结
- JavaScript的strict模式与with关键字介绍
- javascript获取元素样式必杀技
- javascript为下拉列表动态添加数据项
- javascript中拼接HTML字符串的最快、最好的方法
- VS2008中使用JavaScript调用WebServices
- JavaScript中伪协议javascript:使用探讨
- Javascript基础教程之JavaScript语法
- 一个JavaScript处理textarea中的字符成每一行实例