Error in render: "TypeError: Cannot read property 'state' of undefined"
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta = this.delta.bind(this);
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
3.5
6
// way #1 - recommended
// puting .bind(this) after using the reference
<input onChange={this.onInputChange.bind(this)} placeholder="First Name" />
// way #2
// adding this line for each method you use
constructor(){
this.onInputChange = this.onInputChange.bind(this)
}
Thank you!
6
0
3.86
7
You should pass a arrow function instead of regular function : const delta=()=>{
this.setState((preCount)=>{
preCount=this.state.count+1;
}
}
Thank you!
7
0
Are there any code examples left?
New code examples in category Javascript
-
Javascript 2023-04-21 22:52:36
-
Javascript 2022-03-27 22:25:20 javascript download string as file
-
Javascript 2022-03-27 21:40:22 sort numbers in array javascript
-
Javascript 2022-03-27 21:20:04 compare two arrays and return the difference javascript
-
Javascript 2022-03-27 21:15:02 javascript regex french phone number
-
Javascript 2022-03-27 21:05:03 cypress custom error message
-
Javascript 2022-03-27 21:00:05 create element javascript with id
-
Javascript 2022-03-27 20:40:57 feather icons react
-
Javascript 2022-03-27 20:20:01 how to make graphql request in axios
-
Javascript 2022-03-27 20:15:07 bootstrap validator password and confirm password