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
}
}
source
share