LoginSignup
0
0

More than 3 years have passed since last update.

React学習アウトプット(redux-container)

Posted at

今回はreduxにおけるcontainerについて。

containerの役割は、明示的にStoreの内容を変更するために行う作業。

ただし、今現在ではHooksを使う方が圧倒的に記述量、ファイル数が減るためHooksを使う方がおススメらしい。

まぁいつか使う時が来たときに備忘録も兼ねて書いていきます。

import { connect } from 'react-redux'
import { compose } from 'redux'
import Class from 'Class.jsx'

まずは、import { connect } from 'react-redux'import { compose } from 'redux'が必要になる。

また、対象とするクラスコンポーネントが必要になる。

今回は例としてimport Class from 'Class.jsx'としている。

次にmapStateTpPropsmapDispatchToPropsの2つが必要となる。

これら2つはuseStateuseDispatchと同じ役割を果たす。

import { connect } from 'react-redux'
import { compose } from 'redux'
import Class from 'Class.jsx'

const mapStateTpProps = state => {
  return {
    users: state.users
  }
}

const mapDispatchToProps = dispatch => {
  return {
    actions: {
      signIn() {
        dispatch(アクション)
      }
    }
  }
}

最後にcomposeconnectを使ってこれらのアクションが行えるようにする。

import { connect } from 'react-redux'
import { compose } from 'redux'
import Class from 'Class.jsx'

const mapStateTpProps = state => {
  return {
    users: state.users
  }
}

const mapDispatchToProps = dispatch => {
  return {
    actions: {
      signIn() {
        dispatch(アクション)
      }
    }
  }
}

export default compose(
  connect(
    mapStateTpProps,
    mapDispatchToProps
  )
)(Class)

composeの中でconnectを使い、connectの引数にはmapStateTpPropsmapDispatchToPropsを渡す。最後に対象のクラスコンポーネントを渡す。

これで準備はOK。

後は対象のクラスコンポーネントを以下のようにする。

import React, {Component} from 'react'

export default class Class extends Component {
  render() {
    console.log(this.props.users)
    console.log(this.props.actions)
  }
}

Componentをインポートし、this.propsでコンテナーで定義したものを参照できる。

感想としてはまぁ使う場面は少ないのかなと思います。

やはりクラスコンポーネントに変えてさらに継承も行わなきゃいけないし、継承を行うために色々記述しなければいけないので当分はHooksを使っていきます。

アウトプットは大事!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0