今時のreact reduxの書き方

constructorいらなくね?

old
export default class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: "Hello!!"
    }
  }
new
export default class Hello extends React.Component {
  this.state = {
    message: "Hello!!"
  }

clickイベントはbindしない

old
export default class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }
    this.increment = this.increment.bind(this);
  }
  increment() {
    this.setState({ count: this.state.count + 1 });
  }
  render() {
    return (
      <div onClick={this.increment}>count:{this.state.count}</div>
    );
  }
}

new
export default class Hello extends React.Component {
  this.state = {
    count: 0
  }
  increment = () => this.setState({ count: this.state.count + 1 });
  render() {
    return (
      <div onClick={this.increment}>count:{this.state.count}</div>
      //または onClick={()=> this.increment()}
    );
  }
}

mapStateToPropsとかmapDispatchToPropsとかは省略していく

old_container
import React from 'react'
import { connect } from 'react-redux'
import Hello from 'components/Hello'
import { increment } from 'actions/increment'

function mapStateToProps(state) {
  return {
      count: state.increment.count,
      text: state.increment.text
  };
}

function mapDispatchToProps(dispatch) {
  return {
    increment: (text) => { dispatch(increment(text)) }
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Hello)
new_container
import React from 'react'
import { connect } from 'react-redux'
import Hello from 'components/Hello'
import { increment } from 'actions/increment'

export default connect(
  state => ({
    count: state.increment.count,
    text: state.increment.text
  }),
  { increment }
)(Hello)

自分がreact触り始めてから2年になるのかな?
ちょっとずつ昔と色々変わってきてるんだなぁ〜
最近はボイラプレートを眺めて色々自分のリポジトリで試している感じです

この書き方おかしくね?とか、最近はこんな感じで書くとイケてるよってのがあれば教えて欲しいっす!

Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.