티스토리 뷰

Node.js/react

Redux - connect

kkoon9 2020. 9. 28. 00:08

React의 Component자체는 Redux의 흐름에 타는 것이 불가능 하다.

흐름에 타기 위해서는 react-redux에서 제공하는 connect라고 불리는 함수를 이용한다.

먼저, Component가 Store로부터 무언가 정보를 받는 경우, 그걸 props를 통해 받는다.

props는 immutable 하므로 상태가 변경될 때마다 새로운 Component가 다시 만들어진다

이것을 염두에 둔 후에, connect를 실행하고 있는 주변 코드를 보자.

  1. Store가 가진 state를 어떻게 props에 엮을 지 정한다.
    (이 동작을 정의하는 함수는 mapStateToProps라고 불린다.)
  2. Reducer에 action을 알리는 함수 dispatch를 어떻게 props에 엮을 지 정한다.
    (이 동작을 정의하는 함수는 mapDispatchToProps라고 불린다)
  3. 위에 두가지가 적용된 props를 받을 Component를 정한다
  4. Store와 Reducer를 연결시킬 수 있도록 만들어진 Component가 반환값이 된다

connect(mapStateToProps, mapDispatchToProps)(Component)라고 쓰인걸 보면 좀 독특하다고 생각할 수 있겠지만, 결국 최종적인 반환값은 4번과 같다.

components/auth/Register.js

import React, { Fragment, useState } from 'react';
import { connect } from 'react-redux';
import { Link, Redirect } from 'react-router-dom';
import { setAlert } from '../../actions/alert';
import { register } from "../../actions/auth";
import PropTypes from 'prop-types';

const Register = ({ setAlert, register, isAuthenticated }) => {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
    confirm_password: ""
  });

  const { name, email, password, confirm_password } = formData;
  const onChange = e => {
    setFormData({ ...formData, [e.target.name]: e.target.value })
  }
  const onSubmit = async e => {
    e.preventDefault();
    if (password !== confirm_password) {
      setAlert('Password do not match', 'danger', 3000);
    } else {
      register({ name, email, password });
    }
  }

  if (isAuthenticated) {
    return <Redirect to="/dashboard" />;
  }

  return (
    // 생략
  );
};

Register.propTypes = {
  setAlert: PropTypes.func.isRequired,
  register: PropTypes.func.isRequired,
  isAuthenticated: PropTypes.bool,
}
const mapStateToProps = (state) => ({
  isAuthenticated: state.auth.isAuthenticated
});

export default connect(mapStateToProps, { setAlert, register })(Register);

mapStateToProps

const mapStateToProps = (state) => ({
  isAuthenticated: state.auth.isAuthenticated
});

인수로 전달된 state는 전체를 의미한다는 것에 주의해야 한다.

isAuthenticated<Register isAuthenticated={state.auth.isAuthenticated} /> 로 들어가는 것이다.

mapDispatchToProps

Reducer를 통해 store를 변경하려면 만든 action을 dispatch라는 함수에 넘겨줘야만 한다.

이렇게 하면 모든 Reducer가 실행 된다.

Reducer에 switch문으로 분기를 나눈 것은 바로 이 때문이다. Reducer는 관계없는 action을 무시하고, 자기에게 주어진 action만을 처리하도록 되어있어야만 한다.

bindActionCreators

mapDispatchToProps를 bindActionCreators라는 함수로 생략이 가능하다.

다음 코드와 같이 사용이 가능하다.

export default connect(mapStateToProps, { setAlert, register })(Register);


references

kkoon9/Full-Stack-With-javascript

아마 이게 제일 이해하기 쉬울걸요? React + Redux 플로우의 이해

'Node.js > react' 카테고리의 다른 글

react-redux Flow  (0) 2020.09.28
Redux - Reducer, Action  (0) 2020.09.27
Redux - Store  (0) 2020.09.27
Middleware와 thunk  (0) 2020.09.27
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함