mutate a copy of data without changing the original source 一个通过语法糖来避免deep copy带来的性能问题的不改变原数据的库
为了解决deep copies are expensive, and sometimes impossible, 设计出只改变需要改变的对象属性,复用未改变的,这就是这个库的核心思想
update() provides simple syntactic sugar around this pattern to make writing this code easier
import update from 'immutability-helper';const newData = update(myData, {x: {y: {z: {$set: 7}}},a: {b: {$push: [9]}}});
Commands
{$push: array}push()all the items inarrayon the target.{$unshift: array}unshift()all the items inarrayon the target.{$splice: array of arrays}for each item inarrayscallsplice()on the target with the parameters provided by the item. Note: The items in the array are applied sequentially, so the order matters. The indices of the target may change during the operation.{$set: any}replace the target entirely.{$toggle: array of strings}toggles a list of boolean fields from the target object.{$unset: array of strings}remove the list of keys inarrayfrom the target object.{$merge: object}merge the keys ofobjectwith the target.{$apply: function}passes in the current value to the function and updates it with the new returned value.- Shorthand syntax
update({a: 1}, {a: function}). That example would be equivalent to update({a: 1}, {a: {$apply: function}}).
{$add: array of objects}add a value to aMaporSet. When adding to aSetyou pass in an array of objects to add, when adding to a Map, you pass in[key, value]arrays like so:update(myMap, {$add: [['foo', 'bar'], ['baz', 'boo']]}){$remove: array of strings}remove the list of keys in array from aMaporSet.
extend
choose to use the extend functionality to add an $auto and $autoArray command:
import update, { extend } from 'immutability-helper';
extend('$auto', function(value, object) {
return object ?
update(object, value):
update({}, value);
});
var state2 = update(state, {
foo: {$autoArray: {
0: {$auto: {
bar: {$autoArray: {$push: ['x', 'y', 'z']}}
}}
}}
});
