본격적으로 많은 사람들이 사용하고있는 Framework인 React에 대한 정리를 시작해보려한다. React를 배우기 앞서 필수적으로 알아야할 javascript 파트를 정리해보자.
- let과 const는 기본적으로 var을 대체
- 주로 var대신 let과 const를 사용
- 다시 할당하지 않을 변수라면 const를 사용
- 함수를 생성하는 또 다른 방법중에 하나
- 구문이 짧아진다는 장점도 있지만 this키워드의 범위유지에 이점
const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
console.log(materials.map(material => material.length));
// expected output: Array [8, 6, 7, 9]
함수 작성방법
// 일반적인 함수 작성방법
function callMe(name) {
console.log(name);
}
// 화살표 함수 작성방법
const callMe = (name) => {
console.log(name);
}
//파라미터가 없는경우(빈 괄호)
const callMe = () => {
console.log('Max!');
}
//파라미터가 하나인 경우(괄호 생략가능)
const callMe = name => {
console.log(name);
}
//값을 리턴 할 때
const returnMe = name => name
const returnMe = name => {
return name;
}
//=> 둘은 같다.
리액트로 구성한 프로젝트에서 (그리고 최신 자바스크립트에서), 모듈이라 불리는 여러 자바스크립트 파일들에 코드를 분할하게 되는데 이렇게되면 각 파일과 모듈의 목적을 명확히 하는게 가능
유형 두가지
default(unnamed)
export default ...;
import someNameOfYourChoice from './path/to/file.js';
named
해당 export는 이름으로 import가 되어야한다.
import { someData } from './path/to/file.js';
named exports를 import할 때,
다음 구문을 이용해 한 번에 모든 named exports를 import할 수 있음
import * as upToYou from './path/to/file.js';
class는 이전 객체지향언어와 구조가 비슷하므로 정리를 skip한다.
이 둘은 같은 ...
구문을 사용한다.
해당 구문은 보기엔 이래도 연산자 이다.
Spread Operator 사용
주로 배열의 요소들을 가져오거나 배열을 요소들의 리스트로 분해함
사용 예시
// 배열의 요소를 가져온 예시
const oldArray = [1, 2, 3];
const newArray = [...oldArray, 4, 5]; // This now is [1, 2, 3, 4, 5];
//객체에 적용한 예시
const oldObject = {
name: 'Max'
};
const newObject = {
...oldObject,
age: 28
};
//=> 해당 결과는 아래와 같을 것
{
name: 'Max',
age: 28
}
Spread Operator는 배열과 객체를 복제하는데 상당히 유용하다!
하지만 배열과 객체모두 참조형 유형이기에 복사가 어려울수 있다. 고려하자.
Rest Operator 사용
const filter =(...args) =>{
retunr args.filter(el=> el ===1);
}
console.log(filter(1,2,3));
// 예상 output: [1]
배열이나 객체의 값에 쉽게 엑세스할 수 있고 변수에 할당할 수 있음
배열의 예시
const array = [1, 2, 3];
const [a, b] = array;
console.log(a); // prints 1
console.log(b); // prints 2
console.log(array); // prints [1, 2, 3]
객체의 예시
const myObj = {
name: 'Max',
age: 28
}
const {name} = myObj;
console.log(name); // prints 'Max'
console.log(age); // prints undefined
console.log(myObj); // prints {name: 'Max', age: 28}
사용의 예시
const printName = (personObj) => {
console.log(personObj.name);
}
printName({name: 'Max', age: 28}); // prints 'Max'
// 구조분해 압축
const printName = ({name}) => {
console.log(name);
}
printName({name: 'Max', age: 28}); // prints 'Max')
⇒ 동일한 결과를 얻지만 코드가 줄어 들음
Destructuring을 통해,
name
property를 가져와name
이라는 이름의 변수/인수에 저장하고 함수 본문에서 사용