this.state.foo _onChange 和 render() 不同?

this.state.foo is different in _onChange and different in render()?

_onChange方法中,我等待this.state.name中的变化。在更改 _updateArticle 方法时调用:

_onChange() {

        var team = this.getTeamState();
        this.setState({name: team});
        console.log(this.state.name); //"Boston Celtics" //this should have changed but it didn't 
        this.unbind("articles");
        this._updateArticle();
    },

然后在 _updateArticle 中使用这个新状态创建一个新引用。

_updateArticle(team) {
        var teamRef = new Firebase(this.props.baseUrl + team + "/results");
        console.log(this.state.team); // "Boston Celtics" //this should have been new but its not
        this.bindAsArray(teamRef, 'articles');

    },

render 方法中,只是为了检查状态,我将 console.log 用于检查。在render中,this.state.name已正确更新。我的问题是 为什么 this.staterender 函数之外不同?.

根据 API docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

如果你真的想在调用setState后立即访问state,请使用setState方法中的回调参数:

setState(function|object nextState[, function callback])

因此您的代码应如下所示:

_onChange() {
  var team = this.getTeamState();
  this.setState({name: team}, function() {
    console.log(this.state.name);
    this.unbind("articles");
    this._updateArticle(this.state.team);
  });
}

希望这对您有所帮助。