Point directly to "this"

Many people use properties directly on this(for example this.clickCount) instead of an object this.state, and sometimes there are as many as 20 different properties attached directly to this.

Is it this.statepurely for the organization or is there something else? Why don't so many people / projects use this.state?

Both of the following examples work exactly the same.


Sample status code:

class Clicker extends React.Component {

    constructor() {
        super()

        this.state = {
            clickCount: 0
        }

        this._onClick= this._onClick.bind(this)
    }

    render() {
        return (

            <button onClick={this._onClick}>
                Clicked {this.state.clickCount} times
            </button>
        )
    }

    _onClick() {
        this.setState({
            clickCount: this.state.clickCount + 1
        })
    }
}

Sample stateless code:

class Clicker extends React.Component {

    constructor() {
        super()

        this._onClick= this._onClick.bind(this)
    }

    render() {
        return (

            <button onClick={this._onClick}>
                Clicked {this.clickCount ? this.clickCount : 0} times
            </button>
        )
    }

    _onClick() {
        this.clickCount = (this.clickCount ? this.clickCount : 0) + 1
    }
}
+4
source share
2 answers

There are times when you need only instance variables that are not related to state. To do this, just do something like this.<INSTANCE-VARIABLE>.

, , , state this.setState(..).

+3

_onClick, .

_onClick, ( - ).

0

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


All Articles