【问题标题】:this.state.foo is different in _onChange and different in render()?this.state.foo 在 _onChange 中不同,在 render() 中不同?
【发布时间】:2015-08-31 02:06:00
【问题描述】:

_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 放在检查的状态。在renderthis.state.name 已正确更新。我的问题是为什么this.staterender 函数之外是不同的?

【问题讨论】:

    标签: javascript reactjs reactjs-flux react-jsx


    【解决方案1】:

    根据API docs

    setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。调用此方法后访问 this.state 可能会返回现有值。

    如果你真的想在调用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);
      });
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 2019-08-21
      相关资源
      最近更新 更多