Skip to content

Instantly share code, notes, and snippets.

@LeoHeo
Forked from anonymous/index.html
Last active September 6, 2016 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeoHeo/5581fd9e43ee54162bab52fb0c659052 to your computer and use it in GitHub Desktop.
Save LeoHeo/5581fd9e43ee54162bab52fb0c659052 to your computer and use it in GitHub Desktop.
JS Bin// source http://jsbin.com/zeqovisegu
const update = React.addons.update;
/*---------------------------------
immutable.js 기본 사용법(삽입, 수정, 삭제)
React state에서 내부배열을 처리할때는
push는 직접적으로 배열을 건들기때문에 사용하면 안됨
해결방안
- concat으로 새로운 배열 만들고 대체
- facebook이 만든 Immutable Helper인 immutable.js사용
-----------------------------------*/
let array = [
0,1,2,3,4,5
];
print = (data) => {
console.log(JSON.stringify(data, null, 2))
}
/*---------------------------------
push(원소 추가)
- 하나 또는 여러개여도 배열로 감싼다.
-----------------------------------*/
let pushedArray = update(array, {
$push: [6] // [6, 7]
});
print(pushedArray);
/*---------------------------------
set(원소 수정)
- 인덱스를 기준으로 수정
- key: {$set: "value"}
- array가 아니고 object여도 동일
-----------------------------------*/
let object = {
a: '1',
b: '2',
c: {
d: '3',
e: '4',
f: {
change_this_value: '0',
this_stays_same: '6'
}
}
}
let setObject = update(object, {
c: {
f: {
change_this_value: {
$set: '5'
}
}
}
});
let setArray = update(array, {
2: {$set: 5}
});
print(setArray);
print(setObject);
/*---------------------------------
splice(원소 삭제)
- 삭제또한 배열로 넘김
- 인덱스를 기준으로 몇개를 삭제할지 결정
-----------------------------------*/
let changedArray = update(array, {
$splice: [[0, 1], [1, 1]]
});
/*
원하는 결과 => [2, 3, 4, 5]
틀린 결과 => [1, 3, 4, 5]
문제 원인
[0, 1]를 먼저 삭제 => [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]에서 첫번째값을 삭제 => [1, 3, 4, 5]
그래서 결과값이 [1, 3, 4, 5]가 나온다.
$splice: [[0, 1], [1, 1], [2, 1]]를 실행하게 되면
[0, 1, 2, 3, 4, 5] => [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5] => [1, 3, 4, 5]
[1, 3, 4, 5] => [1, 3, 5]
고로 배열값은 [1, 3, 5]
해결방법
그래서 index가 변수일 경우에는 -1, -2를 붙여서 실행
$splice: [[0,1], [1-1, 1], [2-1, 1]]
*/
print(changedArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment