Im create simple class and take this error. What wrong with using methot with parameters in class?
its pure value that i give to method.
class ClassCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.changeCount = this.changeCount.bind(this);
}
changeCount (value) {
this.setState({count: value})
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.changeCount(this.state.count + 1)}>Increment</button>
<button onClick={this.changeCount(this.state.count - 1)}>Decrement</button>
</div>
)
}
}
export default ClassCounter
Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
at ClassCounter (http://localhost:3000/static/js/bundle.js:105:5)
at div
at App
>Solution :
Attribute onClick expects a function to execute, instead, you were passing the output of the function which is undefined. Don’t call the function inside onClick, instead pass it to be executed on the event.
Here is how you can fix it
<button onClick={(e) => this.changeCount(this.state.count + 1)}>
Increment
</button>
<button onClick={(e) => this.changeCount(this.state.count - 1)}>
Decrement
</button>