ReactJS this.setState()与this.state.myvar不同步

Gia*_*Elk 11 reactjs

在组件中的这个ReactJS代码中,我希望this.setState( {b_MyPartyCat: value} )更新,this.state.b_MyPartyCat因此两个console.log语句updatePartyCategory()显示相同的值,但它们不会.

var MyIconButton = React.createClass({

  handleSubmit: function(e) {
    e.preventDefault();

    var b_buttonOn = false;
    if (this.props.pressed === true) {
      b_buttonOn = false;
    }
    else {
      b_buttonOn = true;
    }
    this.props.updateFilter( b_buttonOn ); 
  },

  render: function() {   
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input type="image" src={this.props.pressed ? this.props.onpic : this.props.offpic }></input>
        </form>
      </div>
    );
  }
});


var MyPartyCatButton = React.createClass({

  render: function() {
    return (
      <MyIconButton pressed={this.props.pressed} updateFilter={this.props.updateFilter} onpic="static/images/icon1.jpeg" offpic="static/images/off-icon.jpg"/>
    );
  }
});

//
// Main App view
var MyHomeView = React.createClass({
  getInitialState: function() {
    // This is where I'll eventually get data from the server.
    return {
      b_MyPartyCat: true
    };
  },

  updatePartyCategory: function(value) {
    // Eventually will write value to the server.
    this.setState( {b_MyPartyCat: value} );

    console.log("INSIDE: MyHomeView() updatePartyCategory() value = " + value );
    console.log("INSIDE: MyHomeView() updatePartyCategory() this.state.b_MyPartyCat = " + this.state.b_MyPartyCat );

  },

  render: function() {
    return (
        <div>
         <MyPartyCatButton pressed={this.state.b_MyPartyCat} updateFilter={this.updatePartyCategory}/>
        </div>

        // Eventually will have 3 other categories i.e. Books, Skateboards, Trees !
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

Bri*_*and 42

setState实际上排队状态更新.如果你想在它实际执行后做一些事情,你可以传递一个回调作为第二个参数.

updatePartyCategory: function(value) {
    this.setState({b_MyPartyCat: value}, function(){
        console.log(this.state.value === value); // true
    }.bind(this));
},
Run Code Online (Sandbox Code Playgroud)

  • 是的,有意使用组件作为上下文调用回调. (2认同)