[React.js] 단숨에 리덕스 익히기 :: react-redux

반주부·2021년 7월 19일
0

React.js

목록 보기
5/7
post-thumbnail

글로벌 이벤트라고 생각하면 편해요.
실제는 그렇지 않겠지만 스토어는 리듀서들을 가진 오브젝트고, 실제 데이터는 리듀서에 들어있다고 생각해보세요. store.reducer.data

파일 하나로 끝낼께요.

import React from 'react';
import { Provider, useDispatch, useSelector } from 'react-redux';
import { createStore, combineReducers } from 'redux';

/////////////////////////////////////////
//
// Main
//
/////////////////////////////////////////

function Main() {
    const dispatch = useDispatch();

    // 원래는 store가 아닌 state임. 이해를 돕기 위해 store로 작성함.
    const { value } = useSelector((store) => store.myReducer);

    return (
        <div>
            <input type="checkbox" checked={value}></input>
            <input
                type="button"
                value="myReducer Toggle"
                onClick={() => dispatch({ type: 'myReducer.toggle' })}
            ></input>
        </div>
    );
}

/////////////////////////////////////////
//
// Reducer
//
/////////////////////////////////////////

const initialState = {
    value: false,
};

function myReducer(state = initialState, action) {
    switch (action.type) {
        case 'myReducer.toggle':
            return { ...state, value: !state.value };
        default:
            return state;
    }
}

/////////////////////////////////////////
//
// App
//
/////////////////////////////////////////

function App() {
    return (
        <Provider store={createStore(combineReducers({ myReducer }))}>
            <Main />
        </Provider>
    );
}

export default App;

리듀서는 이벤트 핸들러 같죠? 액션을 받아서 처리합니다.
case 문에 그냥 'toggle'이라고 안 쓰고 'myReducer.toggle'이라고 쓴 이유는 리듀서가 많을 경우 액션을 dispatch하면 모든 리듀서가 호출되기 때문이에요.
즉, 다른 리듀서에 'toggle'을 넣으면 거기서도 처리가 되요.

  1. Main이라는 함수 컴포넌트를 Provider로 감싸고 리듀서를 묶어서 store에 넘겨요.
  2. Main에서 버튼을 클릭하면 액션을 dispatch 해요.
  3. 리듀서에서 처리하고 state를 리턴하면 useSelector로 변경된 값이 들어와요.

액션은 이벤트 객체, 리듀서는 핸들러, 스토어는 글로벌 이벤트!

profile
반은 직장인, 반은 주부

0개의 댓글

관련 채용 정보