본문 바로가기
KOSTA교육/수업

[80/100] 240806

by 이원혁 2024. 8. 6.
반응형

React

 

=============================================================================
프라미스(promise)
=============================================================================
- js에서 제공하는 비동기를 간편하게 처리할 수 있게 도와주는 객체
   https://velog.io/@syoung125/JS-Promise%EB%9E%80
   https://velog.io/@gnoeyah/React-API%ED%86%B5%EC%8B%A0Axios
- 설치
   npm install axios
- axios.get ('https://api.example.com/detail' )   
- axios.post('https://api.example.com/detail', postData                 )
- axios.get ('https://api.example.com/detail', { headers:{"키":"값"}  } )
  .then ( () => {} )
  .catch( () => {} )
 
------------------------------------------------------GET전송예
import axios from 'axios';
axios.get('https://api.example.com/detail')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('오류 발생:', error);
  });
------------------------------------------------------POST전송예
import axios from 'axios';
const userVO = {
    name: 'kim',
    age: 30
};
axios.post('https://api.example.com/detail', userVO)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('오류 발생:', error);
  });
------------------------------------------------------GET + Header
import axios from 'axios';
axios.get('https://api.example.com/detail', {
    headers: {"Authorizatio":"1111"}
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('오류 발생:', error);
  });
------------------------------------------------------공통:인스턴스생성
import axios from 'axios';
const myAxios = axios.create({
    baseURL: 'https://api.example.com',
    timeout: 1000,
    headers: { 'X-Custom-Header': 'foobar' }
});
myAxios.get('/detail')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('오류 발생:', error);
  });
------------------------------------------------------axios + async/await
import axios from 'axios';
async function myGetData() {
  try {
        const response = await axios.get('https://api.example.com/detail');
        console.log(response.data);
  } catch (error) {
        console.error('오류 발생:', error);
  }
}
myGetData();


=============================================================================
[HOOK] useEffect()
=============================================================================
- React의 함수형 컴포넌트에서 (사이드 이펙트)를 수행하기 위해 사용하는 Hook
- (사이드 이펙트) : 컴포넌트가 렌더링될 때마다 수행되어야 하는 작업
                  : ex) 데이터 가져오기, DOM 조작, 구독 설정 등
- 기본적으로 컴포넌트가 마운트되거나 업데이트될 때마다 실행
- 두 번째 인자
        :빈배열 []          :: 컴포넌트가 처음 마운트될 때만 useEffect 실행
        :특정값배열 [arr]   :: 값이 변경될 때만 useEffect 실행
- useEffect(() => { //TODO
                    return () => { };
                  } , [___]);

------------------------------------------------------
useEffect(() => {
  console.log('count 값이 변경될 때만 실행됩니다.');
}, [count]);
------------------------------------------------------
import React, { useEffect } from 'react';
function MyComponent() {
    useEffect(() => {
        console.log('사이드 이펙트 코드 : 컴포넌트 마운트or업데이트될 때마다 실행');
        return () => {
        console.log('컴포넌트 언마운트될 때마다 실행');
        };
    });
    return (
        <div>
        <MyComponent />
        </div>
    );
}


=============================================================================
[HOOK] useCallback
=============================================================================
- 메모이제이션된 콜백 함수를 생성하여 성능 최적화를 도움
  (React 애플리케이션의 불필요한 리렌더링을 줄여 성능을 개선)
- 주로 자식 컴포넌트에 콜백 함수를 전달할 때 불필요한 재렌더링을 방지하기 위해 사용
- useCallback(콜백 함수, 의존성배열);
  useCallback(()=>{}  , []       );
  의존성 배열 내의 값이 변경될 때에만 새로운 콜백 함수 생성
- 주로 자식 컴포넌트에 콜백 함수를 전달할 때 유용  
  (부모 컴포넌트가 리렌더링될 때마다 자식 컴포넌트가 불필요하게 리렌더링되는 것을 방지)

------------------------------------------------------
import React, { useState, useCallback } from 'react';
function MyComponent() {
  const [count, setCount] = useState(0);
  const [text, setText]   = useState('');
  --------------------------
  const myClick = () => {
            setCount(count + 1);
        };
  //count변경시 새로 생성, 변경 없으면 메모이제이션된 이전 생성된 함수 재사용      
  const myClick = useCallback(() => {  
            setCount(count + 1);
        }, [count]);
  -------------------------- 
  return (
    <div>
      <p>증가값: {count}</p>
      <button onClick={myClick}>카운트증가</button>
      <input type="text" value={text} onChange={e => setText(e.target.value)} />
    </div>
  );
}
export default MyComponent;


------------------------------------------------------
-- myClick 내 의존성배열값 count가 변경되지 않는 한
-- ParentComponent가 리렌더링되더라도 ChildComponent는 리렌더링되지 않음
------------------------------------------------------
import React, { useState, useCallback } from 'react';
function ParentComponent() {
  const [count, setCount] = useState(0);

  const myClick = useCallback(() => {
        setCount(count + 1);
  }, [count]);
  return (
    <div>
      <p>Count: {count}</p>
      <ChildComponent onClick={myClick} />             //콜백함수전달
    </div>
  );
}                    
const ChildComponent = React.memo(({ onClick }) => {  //콜백함수수신
    console.log('차일드 렌더링');
    return <button onClick={onClick}>카운트증가</button>;
});
export default ParentComponent;



------------------------------------------------------
import React, { useState, useCallback } from 'react';
function ParentComponent() {
  const [count, setCount] = useState(0);
  const [text, setText]   = useState('');
  
  const myIncrement = useCallback(() => {   //메모제이션(부모만렌더링)
    setCount(c => c + 1);
  }, []);

  const myChange = useCallback((e) => {     //메모제이션(부모만렌더링)   
    setText(e.target.value);
  }, []);

  return (
    <div>
      <p>증가값: {count}</p>
      <ChildComponent onIncrement={myIncrement} onChange={myChange} />
      <input type="text" value={text} onChange={myChange} />
    </div>
  );
}
const ChildComponent = React.memo(({ onIncrement, onChange }) => {
  console.log('차일드 렌더링');
  return (
    <div>
      <button onClick={onIncrement}>카운트증가</button>
      <input type="text" onChange={onChange} />
    </div>
  );
});
export default ParentComponent;



=============================================================================
[HOOK] useNavigate()
=============================================================================
- React Router v6~ 지원되는 Hook
- 함수형 컴포넌트 내에서 페이지 이동 기능 
- 간편하고 직관적인 네비게이션 기능 제공
- 설치
    npm install react-router-dom
- navigate('/home');
- navigate('/about',  { replace:true,  state:{ uid:'kim' } });   
                        replace:true  - 현재 페이지를 새 페이지로 대체(브라우저의 뒤로 가기 기능X)
                        state         - 새 페이지로 이동할 때 전달할 상태 데이터 설정
- location.state를 통해 이전 페이지에서 전달한 데이터 사용 가능
------------------------------------------------------
import React from 'react';
import { useNavigate } from 'react-router-dom';
function HomePage() {
  const navigate = useNavigate();
  const goHome = () => {
    navigate('/home');
  };
  return (
    <div>
      <h1>마이페이지</h1>
      <button onClick={goHome}>Home이동</button>
    </div>
  );
}
export default HomePage;

------------------------------------------------------
const navigate = useNavigate();
// 페이지 이동 시 히스토리를 대체하고 상태 데이터 전달
navigate('/about', { replace: true, state: { uid: 'kim' } });
----------------------
import React from 'react';
import { useLocation } from 'react-router-dom';
function MyNavPage() {
  const location = useLocation();
  const {uid} = location.state || {};
  return (
    <div>
      <h1>마이페이지</h1>
      {uid && <p>{uid}값 수신</p>}
    </div>
  );
}
export default MyNavPage;
------------------------------------------------------




=============================================================================
async/await
=============================================================================
 - 자바스크립트에서 비동기 코드를 작성할 때 사용하는 키워드
 - 비동기 작업을 동기적으로 작동
 - async
     : 함수 선언 앞에 붙여 함수를 비동기 함수로 만듬
       return Promise;  
- await
     : async 함수 내에서만 사용
     : 완료될 때까지 기다리다 Promise 동작 완료 시 Promise의 결과 값 반환
     
------------------------------------------------------ async 사용예
async function getUserData() {
    return '데이터 수신';
}
getUserData().then(response => console.log(response)); 
------------------------------------------------------ async + await 사용예
async function getUserData() {    
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
}
getUserData().then(data => {
        console.log(data);
});

------------------------------------------------------ async + await 사용예
async function getUserData(userId) {
    try {
            const response = await fetch(`https://api.example.com/users/${userId}`);
            if (!response.ok) {
                throw new Error('에러');
            }
            const userVO = await response.json();
            return userVO;
    } catch (error) {
            console.error(error);
    }
}
getUserData(1).then(userVO => {
        console.log(userVO);
});

------------------------------------------------------

package com.boot.demo.lec06;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")                // 모든 경로에 대해 CORS 설정
               
.allowedOrigins("http://localhost:3000")    // 허용할 출처
               
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);                    // 자격 증명 허용
   
}
}

 

CORS 관련

 

CORS란?

Cross-Origin Resource Sharing의 약자로 웹 브라우저에서 다른 출처의 리소스에 접근할 수 있도록 허용하는 매커니즘으로 기본적으로는 다른 출처의 리소스를 제한합니다.

 

 

 

반응형

'KOSTA교육 > 수업' 카테고리의 다른 글

[82/100] 240808  (1) 2024.08.08
[81/100] 240807  (1) 2024.08.07
[79/100] 240805  (0) 2024.08.06
[78/100] 240802  (0) 2024.08.02
[77/100] 240801  (0) 2024.08.01