2-5. 컨테이너 컴포넌트 만들기

우선, 기존의 컨테이너 컴포넌트인 CounterContainer 는 쓸모가 없어졌으니, 삭제를 해주세요.

우리가 이번에 만들 컨테이너 컴포넌트는 CounterListContainer 입니다. 그리고, Buttons 의 경우엔 따로 컨테이너 컴포넌트를 만들어주지 않고, App 컴포넌트를 redux 에 연결시켜서 액션함수들을 연결시켜주고 해당 함수들을 Buttons 컴포넌트에 전달해주도록 하겠습니다.

CounterListContainer 컴포넌트 만들기

우선 CounterListContainer 컴포넌트를 만들어주겠습니다. mapStateToProps 를 통해 props 를 연결해주고, mapDispatchToProps 를 통해 필요한 액션 함수들을 연결시켜주세요.

src/containers/CounterListContainer.js

import CounterList from '../components/CounterList';
import * as actions from '../actions';
import { connect } from 'react-redux';
import { getRandomColor } from '../utils';

// store 안의 state 값을 props 로 연결해줍니다.
const mapStateToProps = (state) => ({
    counters: state.counters
});

/* 
    액션 생성자를 사용하여 액션을 생성하고,
    해당 액션을 dispatch 하는 함수를 만들은 후, 이를 props 로 연결해줍니다.
*/

const mapDispatchToProps = (dispatch) => ({
    onIncrement: (index) => dispatch(actions.increment(index)),
    onDecrement: (index) => dispatch(actions.decrement(index)),
    onSetColor: (index) => {
        const color = getRandomColor();
        dispatch(actions.setColor({ index, color}));
    }
})

// 데이터와 함수들이 props 로 붙은 컴포넌트 생성
const CounterListContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(CounterList);

export default CounterListContainer;

App 컴포넌트 수정하기

다음, App 컴포넌트를 리덕스에 연결시켜주겠습니다. 이 컴포넌트에서는 store에서 필요한 값이 없으니 mapStateToPropsnull 로 설정하고, 버튼을 위한 mapDispatchToProps 를 만드세요.

onCreateonRemove 를 만들고 이를 Button 컴포넌트의 props 로 전달하세요.

import React, {Component} from 'react';
import Buttons from '../components/Buttons';
import CounterListContainer from './CounterListContainer';

import { connect } from 'react-redux';
import * as actions from '../actions';

import { getRandomColor } from '../utils';

class App extends Component {
    render() {
        const { onCreate, onRemove } = this.props;
        return (
            <div className="App">
                <Buttons
                    onCreate={onCreate}
                    onRemove={onRemove}
                />
                <CounterListContainer/>
            </div>
        );
    }
}

// 액션함수 준비
const mapToDispatch = (dispatch) => ({
    onCreate: () => dispatch(actions.create(getRandomColor())),
    onRemove: () => dispatch(actions.remove())
});

// 리덕스에 연결을 시키고 내보낸다
export default connect(null, mapToDispatch)(App);

이번에는 이미 만들어진 컴포넌트를 불러와서 이를 리덕스에 연결시킨게 아니라 파일 하나에서 컴포넌트를 정의하고 바로 연결해주었습니다. 그럴땐, export 하는 부분에서 connect를 통해 리덕스에 연결을 시키면 되겠습니다.

여기까지 진행하시면, 다음과 같이 여러개의 카운터를 관리할수있게 됩니다!지금까지의 코드는 여기서 열람 할 수 있습니다.

results matching ""

    No results matching ""