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

廉价感情. 提交于 2019-12-08 11:08:37

问题


In _onChange method, I wait for a change in this.state.name. On the change _updateArticle method is called:

_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();
    },

then in _updateArticle a new reference is created using this new state.

_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');

    },

In render method however just to check the state I put console.log to check. In render, this.state.name has been updated properly. My question is why is this.state different outside of render function?.


回答1:


As per the 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.

If you really want to access state right after calling setState, use the callback parameter in the setState method:

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

So your code should look like:

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

Hope this helps.



来源:https://stackoverflow.com/questions/32303069/this-state-foo-is-different-in-onchange-and-different-in-render

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!