ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React 기초 - 깊은 복사 함수
    Framework & Library/React 2021. 9. 22. 18:05

    깊은 복사 함수의 사용 이유

    자식 태그도 다시 렌더링을 해야 하는지 확인하는 연산의 최적화를 위해 사용한다. → 깊은 복사는 레퍼런스만 비교하기 때문에 효율적


    spread 연산자

    const a = [1, 2, 3];
    
    const b = [...a]; // a의 값을 b 변수에 복사
    b.push(4); // b의 값 변경
    
    const c = [0, ...a, 4];
    
    console.log(`a의 값은 ${a}`); // 1, 2, 3 출력
    console.log(`b의 값은 ${b}`); // 1, 2, 3, 4 출력
    console.log(`c의 값은 ${c}`); // 0, 1, 2, 3, 4 출력

    concat 연산자

    const a2 = [1, 2, 3]; 
    
    const b2 = a2.concat(4); 
    
    console.log(`a2의 값은 ${a2}`); // 1, 2, 3 출력 
    console.log(`b2의 값은 ${b2}`); // 1, 2, 3, 4 출력

    filter 연산자

    const a3 = [1, 2, 3]; 
    
    const b3 = a3.filter((n) => { return n != 1; }); // boolean 타입을 리턴, true인 값만 걸러냄 
    
    console.log(`a3의 값은 ${a3}`); // 1, 2, 3 출력
    console.log(`b3의 값은 ${b3}`); // 2, 3 출력

    slice 연산자

    const a4 = [1, 2, 3];
    
    const b4 = a4.slice(0, 2);
    
    const c4 = [...a4.slice(0, 2)];
    
    console.log(`a4의 값은 ${a4}`); // 1, 2, 3 출력
    console.log(`b4의 값은 ${b4}`); // 1, 2 출력
    console.log(`c4의 값은 ${c4}`); // 1, 2 출력

    map 연산자

    const a5 = [1, 2, 3]; 
    a5.forEach((n) => { console.log(n); }); // 해당 객체의 원소를 하나씩 순회, 리턴 못함 
    
    const b5 = a5.map((n) => n + 10); // 해당 객체의 원소를 하나씩 순회, 리턴 가능, 가공 가능 
    
    console.log(`a5의 값은 ${a5}`); // 1, 2, 3 출력 
    console.log(`b5의 값은 ${b5}`); // 11, 12, 13 출력
    const users = [ // 기존의 데이터 
        { id: 1, name: "홍길동", phone: "2222" }, 
        { id: 2, name: "임꺽정", phone: "3333" }, 
        { id: 3, name: "이순신", phone: "4444" } 
    ]; 
        
    const updateUserDto = { // 변경하고자 하는 데이터 
        id: 2, name: "강감찬" 
    }; 
    
    const newUser = users.map(user => user.id === updateUserDto.id ? { ...user, ...updateUserDto } : user); // map 연산자를 이용해서 기존 데이터 수정

     

    GitHub - qlsdud0604/react-basic: 리액트의 기초를 학습하는 공간

    리액트의 기초를 학습하는 공간. Contribute to qlsdud0604/react-basic development by creating an account on GitHub.

    github.com

     

    728x90

    'Framework & Library > React' 카테고리의 다른 글

    React 기초 - useRef 함수  (0) 2021.09.22
    React 기초 - useMemo 함수  (0) 2021.09.22
    React 기초 - useEffect 함수  (0) 2021.09.22
    React 기초 - useState 함수  (0) 2021.09.22
    React 기초 - React란?  (0) 2021.09.22

    댓글

Designed by Tistory.