[TIL]reactのupdate()



反応にはupdateが含まれているということです.updateを使用する理由は、オリジナルを破壊せずに奥のオブジェクトを変更するためらしい.
反応公式文書の例から見ると.
const newData = extend(myData, {
  x: extend(myData.x, {
    y: extend(myData.x.y, {z: 7}),
  }),
  a: extend(myData.a, {b: myData.a.b.concat(9)})
});
上記の場合、update
import update from 'react-addons-update';

const newData = update(myData, {
  x: {y: {z: {$set: 7}}},
  a: {b: {$push: [9]}}
});
以下のように簡単に使用できます.
使用可能なコマンドと数式ドキュメントの例で終わります.

Available Commands

$push: array -> push() all the items in array on the target.$unshift: array -> unshift() all the items in array on the target.$splice: array of arrays -> for each item in arrays call splice() on the target with the parameters provided by the item.$set: any -> replace the target entirely.$merge: object -> merge the keys of object with the target.$apply: function -> passes in the current value to the function and updates it with the new returned value.

Examples


- push

const initialArray = [1, 2, 3];
const newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]

//initialArray is still [1, 2, 3].

- splice

const collection = [1, 2, {a: [12, 17, 15]}];
const newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
// => [1, 2, {a: [12, 13, 14, 15]}]

- apply, set

const obj = {a: 5, b: 3};
const newObj = update(obj, {b: {$apply: function(x) {return x * 2;}}});
// => {a: 5, b: 6}
const newObj2 = update(obj, {b: {$set: obj.b * 2}});
// 더 간단하게 구현...(같은 결과)

- merge

const obj = {a: 5, b: 3};
const newObj = update(obj, {$merge: {b: 6, c: 7}}); // => {a: 5, b: 6, c: 7}