리액트

[리액트 - Redux-saga] 리덕스 사가 정리 글

훈츠 2020. 7. 9. 15:27
반응형

 

안녕하세요. 훈츠입니다. 금일은 리덕스 사가에 대해 정리 합니다. 몇몇 한국 블로거들 및 유투버의 도움으로 2일간 학습하며 실습 했는데, 기본이 부족 해서 이해? 하는데 힘들었습니다. 잘안되서 그냥 쓰지 말까? 고민하다가 어느 인도 유투버님의 동영상을 보고 정리 했습니다. 여러므로 감사하네요. ^^ 저도 누군가에게 인도 유투버님 같은 사람이 되고 싶다는 마음에 글을 적어 봅니다. 물론 부족 하지만 초보자가 겪은일을 다시 초보자가 본다면 도움이 될것 같아서요. 


리액트 비동기 처리 

리액트에서 비동기 처리를 하기 위해서 몇가지 방법이 제시 됩니다. 

 1. 클래스 : componentDidMount() 와 callApi 

 2. 함수 : useEffect(()) 

 3. 성큰  (사용 안해봤습니다.)

 4. 리덕스사가


클래스 에서 비동기 처리 

클래스에서 비동기 처리 할때는 아래의 코드를 이용합니다.  

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
class App extends Component {
 
 state = {
    response: '',
    post: '',
    responseToPost: '',
  };
  
  componentDidMount() {
    this.callApi()
      .then(res => console.log(res))
      .catch(err => console.log(err,'test'));
  }
  
//callApi 이용하여, async await 를 통해 데이터를 비동기통신 합니다.     
  callApi = async () => {
    const response = await fetch('/api/user/lkh');
    const body = await response.json();
    if (response.status !== 200throw Error(body.message);
    return body;
  }; 
 render()  
 { //이하 코드 생략 
 
cs


함수 에서 비동기 처리

함수에서 비동기 처리하기 위해서는 useEffect 함수를 이용합니다. 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
export function Register() {
 
useEffect( ()=>{
    console.log('=== useEffect ===');
    async function fetchData() {
      const response2 = await fetch('/api/user/lkh'); //블록킹
      const body = await response2.json() //블록킹
      console.log(body);
      setData(()=>{data = body});
      console.log('완료',data);
    }
    fetchData();
    console.log('동기 실행')
    
  },[]);  // [] 아무것도 안넣어주면 컴포넌트디드마운트와 같다고보면 됨
  
 { //이하 코드 생략 
 
cs

 

마운트 될때만 실행하고 싶을때 ,[] 추가

useEffect( () =>{

 console.log('랜더링이 되었습니다.');

},[] );

 

특정값이 변화 될때만 실행하고 싶을때 ,[변수] 추가

useEffect( () =>{

 console.log('랜더링이 되었습니다.');

},[변수] );

 

useEffect 는 렌더링되고 난 직후마다 실행되며, 두 번째 파라미터 배열에 무엇을 넣는지 에 따라 실행 조건이 달라집니다. 

 


리덕스 사가 에서 비동기 처리

리액트 리덕스 설치 및 세팅 합니다.

npm install -s redux-saga

 

리덕스 사가 세팅 

 

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reducer from './store/reducer';
import createSagaMiddleware from 'redux-saga'// redux-saga 가져오기
import  {watchLogin} from './sagas/saga';
 
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux'// applyMiddleware 추가
 
const sagaMiddleware = createSagaMiddleware();
const store = createStore(reducer,applyMiddleware(sagaMiddleware) );
 
//반드시 store 밑에서 실행 해줘야 함. 
sagaMiddleware.run(watchLogin); 
 
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
 
 
 
 

위와같이 세팅 해주고, sagas 라는 폴더를 만들고 그안에 saga.js 파일을 만듭니다. 

아래와 같이 코딩 해줍니다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
import {takeEvery,takeLatest, put, call, delay} from 'redux-saga/effects'//사용하는 함수만 불러옵니다.  
 
function* AsyncAgeUP( ){
    yield delay(1000); //1초 대기 합니다. 
    yield put({type:'AGE_UP_SYNC', value : 1}); //PUT은 DISPATCH와 같고 AGE_UP_SYNC TYPE에 1이라는 값을 보내줍니다. 
}
 
export function* watchLogin( ){
    yield takeEvery('AGE_UP', AsyncAgeUP); //AGE_UP 이라는 DISPATCH가 들어오면 AsyncAgeUP 함수를 실행합니다.
}
 
 
cs

 

 


코드 공유

 

 

rain2002kr/REDUX-SAGA-ExampleCode

Redux-saga Simple example code about counter . Contribute to rain2002kr/REDUX-SAGA-ExampleCode development by creating an account on GitHub.

github.com

 

 

 

 

 

 

 

반응형