Props vs. State

JavaScript/React 2022. 5. 31. 19:32

1. Props vs. State React에서 컴포넌트 재렌더링을 유발하는 데이터에는 Props와 State가 있는데, Props는 함수의 argument, State는 함수의 local variable로 생각할 수 있음. Props State 해당 컴포넌트 내에서 변경할 수 있는가? X O 부모 컴포넌트에서 변경할 수 있는가? O X 자식 컴포넌트 내에서 변경할 수 있는가? X X A. Props 부모 컴포넌트로부터 전해지는(하향식) 읽기 전용 속성. Props를 전달받은 컴포넌트 내부에서 변경 불가하며, 부모 컴포넌트에서 업데이트해 전달받는 것만 가능. Props는 부모 컴포넌트의 State이기 때문에 Props는 읽기 전용이어야 함. 만약, 자식 컴포넌트에서 Props를 변경하게 된다면 동일한 정..

Article Thumbnail
Class

JavaScript 2022. 5. 26. 22:50

1. 클래스(Class) A. 클래스의 정의 class Rectangle { constructor(height, width) { // 생성자 함수 this.height = height; this.width = width; } get area() { // Getter return this.calcArea(); } calcArea() { // 메서드 return this.height * this.width; } } 객체(instance)를 생성하기 위한 템플릿 '함수'로, 선언식 또는 표현식으로 정의가 가능함. ① Class 선언식 class Rectangle { ... } class 선언식은 호이스팅될 때 초기화가 되지 않으므로 class를 선언한 뒤에 사용할 수 있음에 주의! ② Class 표현식 let..

Article Thumbnail
React Hooks

JavaScript/React 2022. 5. 23. 20:04

1. 함수형 컴포넌트 vs. 클래스형 컴포넌트 /* 1. Welcome 컴포넌트: class 표현 */ class WelcomeC extends React.Component { render() { return Hello, {this.props.name}; }; }; /* 2. Welcome 컴포넌트: 함수 표현 */ function WelcomeF ( {name} ) { return Hello, {name}; } A. Props 값 전달하기 const props = { name: "Sara" } 위와 같은 props를 컴포넌트에 전달하기 위해서는... ① 함수형 컴포넌트 function WelcomeF ( {name} ) { return Hello, {name}; } /* 1. 함수 실행식 이용 */ R..

Article Thumbnail
React 기초

JavaScript/React 2022. 5. 17. 20:48

1. 사용자 정의 컴포넌트 구성 /* 1. Welcome 컴포넌트: class 표현 */ class Welcome extends React.Component { render() { return Hello, {this.props.name}; }; }; /* 2. Welcome 컴포넌트: 함수 표현 */ function Welcome (props) { return Hello, {props.name}; } JSX에서 처럼 작성된 코드에서 Welcome 컴포넌트가 호출되는데, JSX의 속성(여기서는 name, id, className)은 props라는 객체의 한 속성으로 전달됨. Welcome의 render() 내부에서 console.log(this)를 넣으면 위와 같이 props 객체를 볼 수 있음. Reac..

Article Thumbnail
Shallow Copy vs. Deep Copy

JavaScript 2022. 5. 13. 23:17

1. 얕은 복사(Shallow Copy) field-by-field copy라고도 하며, 만약 복사하려는 값이 참조형 자료(배열, 객체, 함수 등)라면 원본의 주소를 복사(참조)하고, 원시형 자료라면 원본의 값을 그대로 복사하는 방법. ① 배열: Array.slice(), Array.from(), Array.map(), ... 등 Array 메서드, [ ...Array ] ② 객체: Object.assign(), { ... Object } A. 얕은 복사의 예 const arr = [ 1, 2, 3, 4 ]; const shallowArr = arr.slice(); console.log( shallowArr === arr ); // false 1차원 배열, 객체는 얕은 복사만으로도 원본을 변경하지 않고 ..

Article Thumbnail
Iterable과 Iterator

JavaScript 2022. 5. 10. 21:40

const obj = { string: "test", number: 123, array: [1, 2, 3, 4], method: function(param) { return param + 1 } } Object 객체에 대해 for ... of 반복문을 사용하면 위와 같은 에러 메시지가 뜸. Object인 객체 obj는 반복가능한(iterable) 객체가 아니기 때문에 for ... of 반복문을 사용할 수 없음. 1. Iterable Protocol [Symbol.iterator] 메서드를 가지고 있는 객체는 iterable이다. for..of 구조에서 어떠한 값들이 loop 되는지 등의 iteration 동작을 정의하는 방법. 배열과 문자열에 대해서는 for ... of 반복문을 사용할 수 있는데, 배..

Article Thumbnail
Optional Chaining

JavaScript 2022. 5. 5. 23:03

1. Optional Chaining # if (obj.someMethod()) { ... }; A.B() 또는 A.B처럼 chaining의 형식으로 메서드를 실행하거나, 속성을 선택하려고 할 때 A가 undefiened일 경우 "B is not a function"과 같은 오류 메시지가 출력됨. 따라서 그 전에 A가 존재하는지 먼저 확인을 해야 함. if (obj && obj.someMethod()) { ... }; 위 코드처럼 "A가 존재하고, A.B()가 true"와 같은 조건문으로 A가 정의되었는지 먼저 검증을 해줘야 함. if (obj?.someMethod()) { ... }; 하지만 A?.B처럼 optional chaining을 이용하면 B 메서드, 속성에 접근하기 전에 먼저 A가 undefi..

IndexedDB 활용하기

JavaScript 2022. 5. 1. 19:53

2022.04.25 - [Front-End 학습/Javascript] - IndexedDB 1. IndexedDB는 비동기적으로 작동 Todo 앱에서 각 할일을 완료 체크하면 해당 할일 HTML Element를 이용해, indexedDB에서 해당 데이터를 검색한 결과를 얻으려고 함. 그렇게 하기 위해 아래와 같이 두 함수를 만듦. // 1. index Key로 DB를 탐색해 결과를 반환하는 함수 function findTaskDB(indexKey, indexValue) { let transaction = db.transaction(["task"], "readwrite"); let taskObjectStore = transaction.objectStore("task"); let indexSearchRequ..

Article Thumbnail
Array.prototype.reduce()

JavaScript 2022. 4. 27. 15:19

arr.reduce(reducer, initialValue); /* reduce()의 콜백함수 */ function reducer (accumulator, current, currentIndex) { ... return accumulator; }; reduce()의 콜백함수는 ① 누산기(accumulator): reduce()에 initialValue가 제공될 경우 initialValue, 아니면 배열의 첫번째 요소 arr[0] ② 현재값(current) - reduce()에 initialValue가 제공될 경우 배열의 첫번째 요소 arr[0], 아니면 배열의 두번째 요소 arr[1] - 콜백함수에 currentIndex가 제공될 경우 arr[currentIndex] ③ 초기값(initialValue):..

IndexedDB

JavaScript 2022. 4. 25. 20:08

Todo 앱의 할일 목록을 관리하기 위해 Local Storage를 사용했으나, 데이터를 저장할 때마다 JSON.stringify()를 이용해 객체를 문자열로 변환시켜주는 과정이 필요하고, 객체 내부의 객체도 JSON.stringify()로 변환이 가능하나, HTML Element같은 객체는 제대로 변환이 불가능하고, Local Stroage의 용량은 최대 10MB 등의 단점으로 IndexedDB를 사용해보기로 함. ※ JSON.strigify()로 HTML Element 변환 저장이 가능하나 일반적인 객체를 저장하는 것만큼 간단하지 않음 How to JSON.stringify a dom element? 1-1. 데이터베이스 열기 // user-Todo라는 이름의 데이터베이스를 불러옴 let reques..

Article Thumbnail