혼자 적어보는 노트

[React]react에서 redux connent 코드 간소화 본문

React

[React]react에서 redux connent 코드 간소화

jinist 2021. 12. 8. 21:25
import React, { Component } from "react";
import Counter from "../components/Counter";
import { connect } from "react-redux";
import * as counterActions from "store/modules/counter";

class CounterContainer extends Component {
  handleIncrement = () => {
    this.props.increment();
  };

  handleDecrement = () => {
    this.props.decrement();
  };
  render() {
    const { handleIncrement, handleDecrement } = this;
    const { number } = this.props;
    return (
      <Counter
        onIncrement={handleIncrement}
        onDecrement={handleDecrement}
        number={number}
      />
    );
  }
}

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

const mapDispatchToProps = (dispatch) => ({
  increment: () => dispatch(counterActions.increment()),
  decrement: () => dispatch(counterActions.decrement()),
});

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

cunnect에 담을 함수를 따로 쓰지 않고 담아서 사용하면 아래와 같이 코드를 간소화시킬 수 있다.

 

 

const mapStateToProps = ;

const mapDispatchToProps = ;

export default connect(
  (state) => ({
    number: state.counter.number,
  }),
  (dispatch) => ({
    increment: () => dispatch(counterActions.increment()),
    decrement: () => dispatch(counterActions.decrement()),
  })
)(CounterContainer);

 

bindActionCreator() 사용

import React, { Component } from "react";
import Counter from "../components/Counter";
import { connect } from "react-redux";
import * as counterActions from "store/modules/counter";
import { bindActionCreators } from "redux";

class CounterContainer extends Component {
  handleIncrement = () => {
    const { CounterActions } = this.props;
    CounterActions.increment();
  };

  handleDecrement = () => {
    const { CounterActions } = this.props;
    CounterActions.decrement();
  };
  render() {
   
   //생략
}

export default connect(
  (state) => ({
    number: state.counter.number,
  }),
  (dispatch) => ({
    CounterActions: bindActionCreators(counterActions, dispatch), 
  })
)(CounterContainer);
Comments