Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Render methods should be a pure function of props and state. But i just use function parameter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading