본문 바로가기
Programming/Javascript

React강좌3 - Redux5. react-redux를 이용한 store연결

by Wilkyway 2020. 8. 9.
반응형

1. Provider: 서비스 제공 컴포넌트

예)

<Provider store={store}>

   <App/>

<Provider>

 

2.컴포넌트를 redux에 연결하는 또다른 함수를 반환함

connect({...options])

예) connect()(Counter)

    store에 연결 된 새로운 컴포넌트 클래스가 반환됨. 옵션이 없으면 this.props.store로 접근 가능

옵션

connect(

   [mapStateToProps],      //state 를 해당 컴포넌트의 props로 연결

   [mapDispatchToProps], //dispatch한 함수를 props로 연결

   [mergeProps],             //state와 dispatch를 동시에 사용할 경우. 잘 사용되지 않음

   [options]                   // pure=true: 불필요한 업데이트를 하지 않음, withRef=false: 잘 사용하지 않음 

)

 

 

3. index.js 에서 Provide 컴포넌트 추가 (강좌 4와 동일)

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

import { createStore } from 'redux';
import { Provider } from 'react-redux';

import reducers from './Reducers';

const store = createStore(reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

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

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

4. components/Counter.js에서 작성

import React, { Component } from 'react';
import Value from './Value';
import Control from './Control';
import { connect } from 'react-redux';
import * as actions from '../Actions';


class Counter extends Component {
    constructor(props) {
        super(props);
        this.setRandomColor = this.setRandomColor.bind(this);
    }

    setRandomColor() {
        const color = [
            Math.floor((Math.random() * 55) + 200),
            Math.floor((Math.random() * 55) + 200),
            Math.floor((Math.random() * 55) + 200)
        ];
        this.props.handleSetColor(color);
    }

    render() {

        const color = this.props.color;
        const style = {
            background: `rgb(${color[0]}, ${color[1]}, ${color[2]})`
        };

        return (
            <div style={style}>
                <Value number={this.props.number} />
                <Control
                    onPlus={this.props.handleIncrement}
                    onSubtract={this.props.handleDecrement}
                    onRandomizeColor={this.setRandomColor}
                />
            </div>
        );
    }
}


const mapStateToProps = (state) => { // 컴포넌트의 state가 아닌 그냥 파라미터 이름(리덕스의 state 와 연결)
    return {
        number: state.counter.number,   // number에 store state의 counter.number 연결
        color: state.ui.color           // number에 store state의 ui.color 연결
    };
};

const mapDispatchToProps = (dispatch) => {  //액션을 연결.
    return {
        handleIncrement: () => { dispatch(actions.increment()) },
        handleDecrement: () => { dispatch(actions.decrement()) },
        handleSetColor: (color) => { dispatch(actions.setColor(color)) }
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Counter);  // 컴포넌트를 redux에 연결하는 또다른 함수 반환
반응형

댓글