HiveBrain v1.2.0
Get Started
← Back to all entries
debugreactCritical

ReactJS: Warning: setState(...): Cannot update during an existing state transition

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
setstateupdatecannotreactjstransitionstateduringexistingwarning

Problem

I am trying to refactor the following code from my render view:

Retour


to a version where the bind is within the constructor. The reason for that is that bind in the render view will give me performance issues, especially on low end mobile phones.

I have created the following code, but I am constantly getting the following errors (lots of them). It looks like the app gets in a loop:

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.


Below is the code I use:

var React = require('react');
var ButtonGroup = require('react-bootstrap/lib/ButtonGroup');
var Button = require('react-bootstrap/lib/Button');
var Form = require('react-bootstrap/lib/Form');
var FormGroup = require('react-bootstrap/lib/FormGroup');
var Well = require('react-bootstrap/lib/Well');

export default class Search extends React.Component {

    constructor() {
        super();

        this.state = {
            singleJourney: false
        };

        this.handleButtonChange = this.handleButtonChange.bind(this);
    }

    handleButtonChange(value) {
        this.setState({
            singleJourney: value
        });
    }

    render() {

        return (
            

                

                    

                        
                            Retour
                            Single Journey
                        
                    

                

            
        );
    }
}

module.exports = Search;

Solution

Looks like you're accidentally calling the handleButtonChange method in your render method, you probably want to do onClick={() => this.handleButtonChange(false)} instead.

If you don't want to create a lambda in the onClick handler, I think you'll need to have two bound methods, one for each parameter.

In the constructor:

this.handleButtonChangeRetour = this.handleButtonChange.bind(this, true);
this.handleButtonChangeSingle = this.handleButtonChange.bind(this, false);


And in the render method:

Retour
Single Journey

Code Snippets

this.handleButtonChangeRetour = this.handleButtonChange.bind(this, true);
this.handleButtonChangeSingle = this.handleButtonChange.bind(this, false);
<Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChangeSingle} >Retour</Button>
<Button href="#" active={this.state.singleJourney} onClick={this.handleButtonChangeRetour}>Single Journey</Button>

Context

Stack Overflow Q#37387351, score: 382

Revisions (0)

No revisions yet.