LoginSignup
33
4

More than 5 years have passed since last update.

Reactの学び2 (オブジェクトへの読み書きを安全に行う)

Posted at

当記事はとてもシンプルです

今までの実装

DoneButton.js
class DoneButton extends React.Component {
  state = { arg: 'Done' }

  handleClick = () => {
    this.setState({
      arg: this.state.arg + 'だーん'
    })
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.arg}
      </button>
    )
  }
}

ReactDOM.render(<Button />, document.getElementById('root'))

今後の実装

DoneButton.js
class DoneButton extends React.Component {
  state = { arg: 'Done' }

  handleClick = () => {
    this.setState((prevState) => {
      return {
        arg: prevState.arg + 'だーん'
      }
    })
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.arg}
      </button>
    )
  }
}

ReactDOM.render(<Button />, document.getElementById('root'))

リファクタリング

DoneButton.js
class DoneButton extends React.Component {
  state = { arg: 'Done' }

  handleClick = () => {
    this.setState((prevState) => ({
      arg: prevState.arg + 'だーん'
    }))
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.arg}
      </button>
    )
  }
}

ReactDOM.render(<Button />, document.getElementById('root'))

handleClickに注目してください。

取り急ぎこれぐらいにしておいて、気付きがあればまた追記します。

33
4
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
33
4