20240514 JS 하기 바쁜데 리액트가 뭐죠?

RingKim1·2024년 5월 14일

TIL

목록 보기
19/77

Today

1. React에서 쓰이는 JS(2)!

화살표 함수

const add = function (a,b) {return a+b;}

const add2 = (a,b) => {return a+b;}
// return이 한 줄인 경우 return과 중괄호 필요 없음.
// 파라미터가 1개일 경우 소괄호도 생략 가능

조건 연산자 = 삼항연산자

const score = 85;
let grade = score >= 80? "A" : "B";

단축평가

논리 연산자를 활용(||, &&, ?., ??)
truthy, falsy

  1. 논리합연산자(||)
    falsy : false, 0, "", null, undefined, NaN
const getUserName = (user) => {
	if(!user.name) { // user.name === undefined
     return "없음";
    }
  	return user. name;
}

const person = {
  age: 30,
};
console.log(getUserName(person)); // "없음"

위 식을 단축평가로 바꿔본다면
// user.name이 falsy 값이면 || 다음 내용을 return
const getUserName = (user) => user. name || "없음";
const person = {
  age: 30,
};
console.log(getUserName(person)); // "없음"

2. 논리곱연산자(&&)
const loggedIn = true;
const userName = "RingKim1";

// loggedIn이 truthy 값이면 && 다음 내용 실행
loggedIn && console.log(`환영합니다 ${userName}님!`)

3. optional chaining(.?)
const user = {
	profile2: {
      name: "RingKim,
      details: {
   		age: 31,
      	location: "제주특별자치도",
      },
	},
    printHello: () => console.log("Hello"),
};

console.log(user.profile.details.age); // cannot read propoerties of undefined

// 값에 접근
console.log(user.profile?.details.age); // undefined

// 함수에 대해
user.printHello1?();

  1. Null 병합 연산자 (??)
  • 논리합 연산자 0과 헷갈리지 않도록!
let userLocation = null;

// 좌변이 null, undefined인 경우에만 우변을 보여줌
console.log(userLocation ?? "없는 위치");
// userLocation ? userLocation : "없는 위치";

ES6 Modules

모듈은 재사용 할 수 있는 함수, 객체 또는 원시 값을 의미

// math.js
export const add = (a, b) => a+b;
// app.js
import {add} from `./math.js`

console.log(add(2,3)); // 5

사용 이유

  1. 스크립트 파일 간의 종속성과 로딩 순서를 수동으로 관리하지 않기 위해!

  2. 코드 캡술화와 충돌방지

  3. 효율적인 코드 로딩

고급 모듈기능

  1. 이름 바꾸기
// add를 가져와서 a로 쓰겠다.
import {add as a} from `./math.js`
  1. 기본 내보내기, 가져오기
// math.js
export default function multiply (x, y) {
  return x * y
}
// app.js
// 가져오는 것이 1개이기 때문에 {} 생략
// M도 아무 이름으로 지을 수 있음
import M from `./math.js`
  1. 전체 내용 가져오기
import * as MathFunctions from `./math.js`

Promise, async/await 👉 참고

2. React


Learn

와 아직 자바스크립트도 모르겠는데 리액트 하려니 머리가 어지럽다...


주절주절

오늘의 점심 : 바나나 + (닭가슴살)볶음밥

profile
커피는 콜드브루

0개의 댓글