2016-11-16 77 views
0

據我所知,這是Redux應該解決的問題,但暫時我試圖在沒有它的情況下完成這項工作。如何更新Render外部的狀態?

當我運行這個,我意識到它卡在一個模式。當我運行render它觸發updateState()從而改變了狀態,即觸發重新渲染,從而引發updateState()等等...

我收到錯誤:

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount. 

是什麼componentWillMount辦?如果我調用<CreateRows />它會更新狀態,但是避免循環,那麼構建這個的最佳方法是什麼?

var CreateRows = React.createClass({ 
    updateState : function(){ 
     this.setState({ 
      'people' : [{'name':'something_else', 'email':'[email protected]'}] 
     }); 
     return (
       <tr> 
        <td>Morgan</td> 
        <td>[email protected]</td> 
       </tr> 

      ) 
    } 

    render: function(){ 
     return (
      <tbody> 
       {this.updateState()} 
      </tbody> 
     ) 
    } 
}); 

回答

0

它不建議在render更新狀態,但部分已經被渲染後,您可以使用componentDidMount方法更新,例如:

var CreateRows = React.createClass({ 
    updateState : function(){ 
     this.setState({ 
      'people' : [{'name':'something_else', 'email':'[email protected]'}] 
     }); 
    }, 
    componentDidMount: function() { 
     this.updateState(); 
    }, 
    render: function() { 
     return (
      <tbody> 
       <tr> 
        <td>Morgan</td> 
        <td>[email protected]</td> 
       </tr> 
      </tbody> 
     ); 
    } 
});