React render/re-render two different versions of s

2019-09-10 10:29发布

问题:

I have an app that is rendering correctly on initial load. It is rendering data from a json obj I'm passing in as a prop. I'm saving the data in an array in state. Later async calls occur. Using setState I update the state accordingly. When React re-renders however it does two passes -- one with the correct, new state that I can see when I step through, then one with the initial state. The initial state render occurs last so I'm left with the same initial state. What gives?

updateTab = React.addons.update(this.state, {
    tabResults: {0: {docs: {$set: data.response.docs}}},
    counts: {$set: data.facet_counts.facet_fields.categories},
    tab: { $set: b }
  });
this.setState(updateTab, this.saveTab);

Then my component looks like:

var TabControls = React.createClass({
  render: function(){
    var tabsum = 0;
    countrow = [];

    function addit(d){
      tabsum = tabsum + d;
    }

    for(o = 0; o < 5; o++){
      if(this.props.counts[o] != null){
        addit(this.props.counts[o]);
      }
    }

    if(this.props.tabID == 0){
        countrow.push(<p className="result-count-large col-sm-6">{tabsum} Results</p>);
    }
    else{
      countrow.push(<p className="result-count-large col-sm-6">{this.props.tabCount} Results</p>);
    }

    return (
      <div className="search-tab-controls container-fluid">
        {countrow}
        <div className="col-sm-6">
          <p>Sort by</p>
          <select className="form-control">
            <option>Relevance</option>
            <option>Recent</option>
          </select>
          <a href="#" className="test"><img src="/img/search/print-icon.jpg" alt="print search results" /></a>
        </div>
      </div>
    );
  }
});

Like I said, I can step through and watch this happen. I watch it set the proper updateTab variable to get pushed to setState. Then I watch my component re-render. The first re-rendering the state is correct. The second re-rendering has the initial all-zero state. I tried putting unique keys on the LIs in the countrow array, that did nothing.