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
CodePudding user response:
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>
CodePudding user response:
change your onClick functions to arrow functions:
<button onClick={() => this.changeCount(this.state.count 1)}>Increment</button>
<button onClick={()=> this.changeCount(this.state.count -1)}>Decrement</button>
when you execute your function in onClick, it will try to change the state, and it is a better approach to create a arrow function outside the render of your class and changing state in that function:
handleIncreament=()=>{
this.changeCount(this.state.count 1)
}
and use it:
<button onClick={handleIncreament}>Increment</button>
because react will create a new function in each render if you use arrow functions in render