React-2

최광희·2023년 10월 31일

React

목록 보기
2/44

React 에서 자주 사용되는 필수 ES6 문법

[학습 목표]

  1. React 개발을 위해서 꼭 필요한 JS문법 중, ES6 문법에 대해 숙지합니다.
  2. 얕은 복사의 개념과, 이를 방지해야 하는 필요성에 대해 설명할 수 있습니다.

상수와 변수

상수(const) : 재할당 안됩니다. 내부 속성값은 수정 가능합니다.
변수(let) : 재할당 가능합니다.

  • 둘 다 block level scope를 가진답니다.
// test1 상수
const a = 1;
let b = 3;
a = 3;
console.log("a", a);
console.log("b", b);
// Assignment to constant variable.
// test2 변수
const a = 1;
let b = 3;
b = 1;
console.log("a", a);
console.log("b", b);
// a 1
// b 1
if (true) {
  var a = 3;
  console.log("a", a);
}

console.log("바깥 a", a);

// a, 3
// 바깥 a, 3 => 다른 언어에서는 undefined가 되어야하지만 block level scope때문에 값이 나옴

블록체인스코프, 함수레벨스코프 알아보기

Object 선언, 단축 속성, 객체 복사

object는 key-value pair 이다.

객체를 선언하는 방법

// 선언방법
const person = {
	name: '르탄',
	age: 21,
	company: 'sparta coding club',
	doSomething: () => {},
}

생략해서 표현하는 방법

const name = '르탄';
const age = 21;

/** 단축속성 : key - value가 일치하면 생략해요. */

// 변경 전
const person = {
	name: name,
	age: age,
	company: 'sparta coding club',
	doSomething: function(){},
}

// 변경 후
const person = {
	name,
	age,
	company: 'sparta coding club',
	doSomething: function(){},
}

복사 주의! (얕은 복사)

const obj1 = { value1: 10 };
const obj2 = obj1; // 얕은 복사
const obj3 = JSON.parse(JSON.stringify(obj1)) // 새로운 주소값을 생성하고 문자열로 풀었다가 다시 객체로 묶어주는 api

obj2.value1 += 1; 

// obj2의 값을 변경 했는데 obj1의 값도 같이 변경이 된다.
console.log(`obj1:`, obj1); // { value1: 11 }
console.log(`obj2:`, obj2); // { value1: 11 }
console.log(`obj3:`, obj3); // { value1: 10 }

결론적으로는, const obj2 = obj1; 이런 식의 복사 방법(얕은 복사)은 주의하셔야 해요! 의도치 않은 변경이 일어날 수 있습니다.

Template Literals

// 일반 텍스트
`string text`

// 멀티라인
`string text line 1
 string text line 2`

// 플레이스 홀더를 이용한 표현식
`string text ${expression} string text`

배열/객체 비구조화 (Array/Object Destructuring)

구조분해 할당이다.

객체의 비구조화(구조분해 할당)

// console.log의 결과를 한번 예측해보세요!
// person 객체 안에 있는 값들이 구조가 해제되어 각각 변수에 할당됩니다.

const person = {
	name: '르탄',
	age: '21'
}

const { name, age } = person;
console.log(`${name}님, ${age}살이시네요!`); // 르탄님, 21살이시네요!
// hello(person)의 결과를 한번 예측해보세요!
// 함수의 입력값 또한 각각 구조가 해제되어 각각 변수에 할당됩니다.
// 특히 이 패턴을 많이 쓸거에요! 기억해주세요.

const person = {
	name: '르탄',
	age: '21'
}

function hello({name, age}) {
	console.log(`${name}님, ${age}살이시네요!`);
}

hello(person); // 르탄님, 21살이시네요!

배열의 비구조화(구조분해 할당)

// 객체에서의 케이스와 마찬가지로 배열도 구조분해 할당이 이루어집니다!
const testArr = [1, 2, 3, 4, 5];
const [val1, val2, val3, val4, val5] = testArr;

console.log(val1);
// 추가 예제

let [name] = ["Tom", 10, "Seoul"];
// let [, age] = ["Tom", 10, "Seoul"];
// let [name, age, region] = ["Tom", 10, "Seoul"];
// let [name, age, region, height] = ["Tom", 10, "Seoul"];
// let [name, age, region, height = 150] = ["Tom", 10, "Seoul"];

전개 연산자 (Spread Operator)

전개연산자(…)를 이용해서 다음과 같이 활용할 수 있습니다.

  • CASE 1
let [name, ...rest] = ["Kwanghee", 31, "Busan"];

console.log("name", name); // name Kwanghee
console.log("rest", rest); // rest [ 31, 'Busan' ]
  • CASE 2
let names = ["Steve", "John"];
let students = ["Tom", ...names, ...names];

console.log("students", students); // students [ 'Tom', 'Steve', 'John', 'Steve', 'John' ]
  • CASE 3
let tom = {
  name: "Tom",
  age: 10,
  region: "Seoul",
};

let steve = {
  ...tom,
  name: "Steve",
};

console.log(tom); // { name: 'Tom', age: 10, region: 'Seoul' }
console.log(steve); // { name: 'Steve', age: 10, region: 'Seoul' }

Arrow Functions

function mysum1(x, y){
    return x + y;
}

const mysum1 = (x, y) => x + y;
const mysum2 = (x, y) => {x, y};
const mysum3 = (x, y) => ({x: x, y: y}); const mysum4 = (x, y) => {
  return {x: x, y: y};
}
const mysum5 = function(x, y) {
  return {x: x, y: y};
};
function mysum6(x, y) {
  return {x: x, y: y};
}

console.log(mysum1(1, 2)); // 3
console.log(mysum2(1, 2)); // undefined (중괄호 생략 안함)
console.log(mysum3(1, 2)); // { x: 1, y: 2 }
console.log(mysum4(1, 2)); // { x: 1, y: 2 }
console.log(mysum5(1, 2)); // { x: 1, y: 2 }
console.log(mysum6(1, 2)); // { x: 1, y: 2 }
profile
나는 사람들을 치료해주는 '약'과 같은 존재가 되고 싶다.

0개의 댓글