Counter 프로젝트에 Redux를 적용해봅시다.


먼저 App 컴포넌트에서 필요하지 않은 부분은 다 삭제하겠습니다. 아래와 같이 작성해주세요.

import React from "react";
import CountButton from "./components/CountButton";
import Number from "./components/Number";
import styled from "styled-components";

const Wrapper = styled.div`
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100px;
  margin-top: 100px;
`;

const ButtonWrapper = styled.div`
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 50px;
`;

const App = () => {
  return (
    <Wrapper>
      <ButtonWrapper>
        <CountButton onClick={} text="+" />
        <CountButton onClick={} text="-" />
      </ButtonWrapper>
      <Number number={} />
    </Wrapper>
  );
}

export default App;

먼저 상태 값을 받아오거나 변경하기 위해서는 해당 컴포넌트에 스토어를 연결해줘야 합니다. 이를 위해 사용하는 것이 connect 함수입니다. connect 함수는 react-redux 라이브러리에 있는 함수로, 복잡한 store 구독 과정을 알아서 처리해주는 함수입니다. 그럼 connect 함수에 대해 알아봅시다.

그럼 App 컴포넌트에 스토어를 연결해봅시다. 아래와 같이 App 컴포넌트를 수정해주세요.

import React from "react";
import CountButton from "./components/CountButton";
import Number from "./components/Number";
import styled from "styled-components";
import { connect } from 'react-redux';
import * as counterActions from './store/reducer';
import { bindActionCreators } from 'redux';

const Wrapper = styled.div`
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100px;
  margin-top: 100px;
`;

const ButtonWrapper = styled.div`
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 50px;
`;

const App = ({ number, counterActions }) => {
  return (
    <Wrapper>
      <ButtonWrapper>
        <CountButton onClick={() => counterActions.increase(number + 1)} text="+" />
        <CountButton onClick={() => counterActions.decrease(number - 1)} text="-" />
      </ButtonWrapper>
      <Number number={number} />
    </Wrapper>
  );
}

const mapStateToProps = state => ({
  number: state.number
})

const mapDispatchToProps = dispatch => ({
  counterActions: bindActionCreators(counterActions, dispatch)
})

export default connect(mapStateToProps, mapDispatchToProps)(App);

하단 부분의 mapStateToProps, mapDispatchToProps, connect 함수는 위에서 다 설명했기 때문에 건너뛰겠습니다. App 컴포넌트 부분을 봅시다. 하단의 스토어의 상태 값과 dispatch 함수에 연결 된 액션 생성자 함수를 props로 매핑시켜주었기 때문에 App 컴포넌트에서는 number와 increase, decrease 함수를 Props로 받습니다. 그럼 컴포넌트 내부에서 위와 같이 상태 값을 출력할 수 있고, 액션 생성자를 호출할 수 있습니다. 이렇게 하고 브라우저에서 버튼을 눌러보세요. Redux 개발자 도구에서 log가 남는 것을 확인할 수 있습니다.