Redux

Miog Yang·2022년 11월 8일
0

Redux 알아보기

1. Acrions

ActionTypes : 액션을 정의, 객체형으로 type이라는 값을 지니고 있어야 한다.

{
type: "INCREMENT"
}

{
type: "DECREMENT"
}

{
type: "SET_COLOR",
color: "black"
}

  • type은 액션의 이름과도 같은 존재이다.


// src/actions/ActionTypes.js


export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const SET_COLOR = 'SET_COLOR';
  • Action의 종류들을 선언한다.(선언시 대문자사용)

import * as types from " ./ActionsTypes "

export로 선언하고 import로 불러온다.




액션생성자 만들기

액션을 만드는 함수를 액션 생성자라고 한다.


import * as types from './ActionTypes';

export const increment = () => ({
    type: types.INCREMENT
});

export const decrement = () => ({
    type: types.DECREMENT
});

// 다른 액션 생성자들과 달리, 파라미터를 갖고있습니다
export const setColor = (color) => ({
    type: types.SET_COLOR,
    color
});
  • increment와 decrement의 경우 지정해줘야하는 필요값이 없으므로 type만 지정된 객체를 만들고 setColor는 색상을 지정해주는 것이므로 파라미터로 color 값을 받고 이 값을 객체안에 넣어준다.



2. Reducer

액션의 type에 따라 변화를 일으키는 함수와 초기상태를 정의한다.

  • 초기 상태를 정의
    const initialState = {
    color: 'black',
    number: 0
    };

// src/reducers/index.js

import * as types from '../actions/ActionTypes';

const initialState = {
    color: 'black',
    number: 0
};
  • reducer 함수는 state와 action을 파라미터로 가지며 switch문을 통하여 action.type에 따라 실행하는 값을 넣어준다.

// src/reducers/index.js

function counter(state = initialState, action) {
    switch (action.type) {
        case types.INCREMENT: 
            return {
                ...state,
                number: state.number + 1
            };
        case types.DECREMENT:
            return {
                ...state,
                number: state.number - 1
            };
        case types.SET_COLOR:
            return {
                ...state,
                color: action.color
            };
        default:
            return state;
    }
};

export default counter;



3. Store만들기

현재 상태를 내장하고 있고 구독(subscripbe)중인 함수들이 상태가 업데이트 될 때 마다 다시 실행되게 해준다.

  • Redux 관련 불러오기
    import { createStore } from 'redux'
    import reducers from './reducers';
  • 스토어 생성
    const store = createStore(reducers);
// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/App';
import './index.css';

import { createStore } from 'redux'
import reducers from './reducers';

const store = createStore(reducers);

ReactDOM.render(
  <App />,
  document.getElementById('root')
);



4. Provider

: react-redux 라이브러리에 내장되어있는, 리액트 앱에 store 를 손쉽게 연동 할 수 있도록 도와준다. Provider컴포넌트를 사용하여 연동할 컴포넌트를 감싸준후 props로 store값을 설정해준다.

  • Redux 관련 불러오기
    import { createStore } from 'redux'
    import reducers from './reducers';
    import { Provider } from 'react-redux';
  • 스토어 생성
    const store = createStore(reducers);
  • 컴포넌트 내에 props설정
    store={store}
import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/App';
import './index.css';

import { createStore } from 'redux'
import reducers from './reducers';
import { Provider } from 'react-redux';

const store = createStore(reducers);

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);



profile
주니어 개발사전 & 프론트엔드 도전기

0개의 댓글