mardi 26 juillet 2016

React setState not working on first try, but works on second?

I have the handleSelection method called when a button is clicked, however, if I click the button once the state does not get set when it gets to this.setState({selectedFoods: newSelections});. Everything else in the method executes correctly (as my various console.logs tell me :) ). When the button is clicked a second time, everything in the method gets executed again and the setState works.

handleSelection: function (e) {
    if (e.target) {
      var selectedFood = e.target.id;
    } else {
      var selectedFood = e;
    }
    console.log(selectedFood);

    if (this.state.foods[selectedFood]) {
      var selections = this.state.selectedFoods;
      var newSelections = selections.concat(selectedFood);
      console.log("newSelections: "+newSelections)
      this.setState({selectedFoods: newSelections});
      console.log("state: "+this.state.selectedFoods)
      this.handleAffinities();
    } else {
      console.log("** "+selectedFood+" **");
    }

  },

Why does everything execute correctly the first time except my setState function? And why it work on the second click?

Aucun commentaire:

Enregistrer un commentaire