react 事始め 11

◾️connect関数

connect関数を使用して、StateやActionと、Componentとの関連付けを行って、Viewのイベントで状態を遷移させて、遷移後の状態を画面に再描画する。まず、react-reduxからconnect関数をインポートする。

次に、定義したいComponentを一つにするので、CounterのComponentの名称を変更し、AppのComponentを削除する。また、Componentに必要となるActionCreatorであるincrement関数とdecrement関数をインポートする。

src/App.js

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { increment, decrement } from '../actions'

class App extends Component {
  constructor(props){
    super(props)
    this.state = { count: 0 }
  }

  handlePlusButton = () => {
    this.setState({ count: this.state.count + 1 })
  }

  handleMinusButton = () => {
    this.setState({ count: this.state.count - 1 })
  }

  render(){
    return (
      <React.Fragment>
        <div>count: { this.state.count }</div>
        <button onClick={this.handlePlusButton}>+1</button>
        <button onClick={this.handleMinusButton}>-1</button>
      </React.Fragment>
      )
  }
}

export default App;

App Classの中にあるconstructorメソッドは、Componentの初期化時に実行されるコールバックであるが、コールバック内の初期化のcountはreducerで行うので削除する。handlePlusButtonhandleMinusButtonもActionCreatorで処理の名称を確保して、そのActionCreatorからreducer内の適切な状態変化を呼ぶことで同じことを実現しているので削除する。

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { increment, decrement } from '../actions'

class App extends Component {
  render(){
    return (
      <React.Fragment>
        <div>count: { this.state.count }</div>
        <button onClick={this.handlePlusButton}>+1</button>
        <button onClick={this.handleMinusButton}>-1</button>
      </React.Fragment>
      )
  }
}

export default App;

この後、render内の処理を実装を行う。