React - Unable to read setState property from null

I know that similar topics are discussed in the field of review.

Using the following component

import React from 'react';
import ReactDOM from 'react-dom';

class Example extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            counter: 0
        }
    }

    addMore() {
        this.setState({
            counter: this.state.counter + 1
        });
    }

    render() {
        return (

            <div onClick={ this.addMore }>
                <p>counter: { this.state.counter }</p>
            </div>

        );
    }
}

if (document.getElementById('example')) {
    ReactDOM.render(<Example />, document.getElementById('example'));
}

When you click div, you getCannot read property 'setState' of null

I know that you can do things like this.addMore.bind(this), but it all seems like a weird extra pattern-style code to make it work.


What is considered the most elegant way to do this? Do people really have to have a preferred method that has their own benefits, other than being a sore eye?

+4
source share
2 answers
addMore = () => {
  this.setState({
    counter: this.state.counter + 1
  });
}

arrow syntax takes care of binding thisfor you

, http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html

+11

this , , this.addMore = this.addMore.bind(this); .

constructor(props) {
    super(props);

    this.state = {
        counter: 0
    }

    this.addMore = this.addMore.bind(this);
}

ES5 React.createClass this, ES6 this .

Bind in Constructor, , React " ".

+7

Source: https://habr.com/ru/post/1675744/


All Articles