React를 배우기 전에 알아야 할 JavaScript 개념

Mar 31 2023
1. 삼항 연산자 이 표현식의 기본 작동 방식은 조건을 먼저 확인하고 조건이 참이면 삼항 연산자( ? ) 뒤의 명령문이 실행되고 그렇지 않은 경우 콜론( : ) 실행됩니다.
Saad를 사용한 JavaScript 개념

1. 삼항 연산자

// Below is the example of ternary operator (?) being used in a conditional 
// expression
condition ? (if condtion is true, run this ):(if condition is false, run this);

이 표현식의 기본 작동 방식은 먼저 조건을 확인하고, 조건이 참이면 삼항 연산자( ? ) 뒤의 명령문이 실행되고 그렇지 않은 경우 콜론( : ) 뒤의 명령문이 실행됩니다.

2. 파괴

const objects = ['table', 'iPhone', 'apple']
const [furniture, mobile, fruit] = objects

다른 예:

const vehicleOne = {
  brand: 'Ford',
  model: 'Mustang',
  type: 'car',
  year: 2021, 
  color: 'red'
}

myVehicle(vehicleOne);

function myVehicle({type, color, brand, model}) {
  const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
}

const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

다음은 또 다른 예입니다.

const myVehicle = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'red'
}

const updateMyVehicle = {
  type: 'car',
  year: 2021, 
  color: 'yellow'
}

const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}

.map() 메서드:

const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)

function myFunction(num) {
  return num * 10;
} 
//this function is called by the .map() method where the numbers array 
 //each element is taken as parameter

.pop()은 배열 끝에 있는 항목을 제거하고 .push()는 배열 끝에 요소를 추가합니다.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi", "Lemon"); // adds Kiwi and Lemon after Mango
fruits.pop(); // removes Lemon at the end of an array

5. 화살표 기능

보다 간단한 방식으로 함수를 생성하는 데 도움이 됩니다.

let hello = () => 'hello' //here we created an arrow function 
                          // assigned it to hello 
                           // this function returns 'hello'

let square = num => num * num // we can ignore bracketts 
                              //if we only have one parameter
                              // num in this case

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

  1. 해결됨 — 완료되면 기능을 수행합니다.
  2. 거부됨 — 수행하려는 기능이 성공하지 못한 경우
  3. Pending — 함수의 결과가 아직 결정되지 않은 경우

.catch () 함수는 약속에서 오류 처리에 사용됩니다.

7. 가져오기 API

fetch('http://example.com/books.json') // fetching the resource URL
  .then(response => response.json()); // calling .json() method on the promise
  .then(data => setState(data)); // updating the state with the JSON data

이 fetch()메소드는 Response 객체로 확인되는 Promise를 반환합니다.

8. 비동기/대기

Async/Await 기능은 약속을 처리하는 더 좋고 깔끔한 방법을 제공합니다. JavaScript는 본질적으로 동기식이며 async/await는 약속이 해결되거나 거부될 때까지 추가 코드 실행을 중지하여 마치 동기식인 것처럼 약속 기반 함수를 작성하는 데 도움이 됩니다.

작동하게 하려면 함수를 선언하기 전에 먼저 async 키워드를 사용해야 합니다 . 예를 들어, async function promise() {}. 함수 앞에 async를 넣는 것은 함수가 항상 약속을 반환한다는 것을 의미합니다.

비동기 함수 내에서 키워드를 사용하여 await해당 약속이 확인되거나 거부될 때까지 코드의 추가 실행을 일시 중지할 수 있습니다. async 함수 내에서만 await를 사용할 수 있습니다 .

이제 예제를 통해 이 섹션을 빠르게 마무리하겠습니다.

async function asyncFunction() {
    let promise = new Promise(resolve => {
        resolve();
    });
    let response = await promise; // further execution will be stopped until the promise is resolved or rejected
    return console.log(response);

function Component() {
    return(
        <div>This is a component</div>
    )
}

export default Component

import Component from './Component'

function App() {
    return (
        <Component />
    )
}

위의 예에서는 Component 라는 구성 요소를 만들고 코드와 함께 내보냈습니다 export default Component. 다음으로 App.js 로 이동하여 다음 코드를 사용하여 구성 요소를 가져옵니다 . import Component from './Component'.

무료코드캠프에서.