Reputation: 153
Hi I am confused about the 'this' keyword in ReactJS. I have the following code here for a simple counter in react.
import React, { Component } from "react";
import ReactDOM from "react-dom";
class ButtonClass extends React.Component {
constructor(props) {
super(props);
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
this.state = { count: 0 };
}
increment() {
this.setState({ count: this.state.count + 1 });
}
decrement() {
this.setState({ count: this.state.count - 1 });
}
render() {
const showCountStatus = this.state.count;
return (
<div>
<p>Click to increrment the button</p>
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
<h1>{showCountStatus}</h1>
</div>
);
}
}
export default ButtonClass;
ReactDOM.render(<ButtonClass />, document.getElementById("root"));
The code works perfectly however, if I change the increment and decrement function to:
increment() {
this.setState({ count: count+ 1 });
}
decrement() {
this.setState({ count: count-1 });
}
Count is not defined error is shown
Any suggestions as to why? Thank you
Upvotes: 0
Views: 1108
Reputation: 36915
As the error message says, there is no count
variable defined.
From what I understood, it seems like you want to increment by one from previous state.
Then you can get a reference to the previous state and use that value to increment by one.
increment() {
this.setState(prevState => ({ count: prevState.count+ 1 }));
}
decrement() {
this.setState(prevState => ({ count: prevState.count-1 }));
}
Refer to State Updates May Be Asynchronous for more details on where prevState
is from and how it is used.
Upvotes: 3
Reputation: 118271
The code which doesn't work, because count
in count + 1
, count - 1
is not from this.state
object count
key. JS is trying to find inside the function scope the variable definition, and it did not find it and throwing the correct error.
So to access the state object key count
, you always need to write it like this.state.count
.
Upvotes: 0