[TIL] React의 update()

choiuhana·2021년 9월 30일
0

TIL

목록 보기
32/37


대략 리액트에 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}
profile
만드는 사람도 사용하는 사람도 편하고 만족하는 '것'을 추구하는 프론트엔드 개발자

0개의 댓글