2016-09-27 113 views
0

我有以下組成部分:陣營組件所呈現舊道具

var Answer = React.createClass({ 

    getInitialState: function(){ 
    return {edit: false, comments: []} 
    }, 

componentWillMount: function(){ 
    $.ajax({ 
     context: this, 
     method: 'GET', 
     url: '/answers/' + this.props.answer.id + '/comments/', 
     success: function(data){ 
      this.setState({comments: data}); 

     } 
    }); 
}, 

render: function(){ 
    return ( 
     <div> 
      //This renders with initial comments in the state, the empty array 
      <Comments comments={this.state.comments} /> 
     </div> 
    ); 
}, 

通知我如何從服務器獲取意見,並把它們保存到狀態,然後將它們作爲道具的意見。問題是道具正在作爲舊狀態傳遞,而不是從服務器獲取的新狀態。我在這裏錯過了什麼?

+0

您的評論組件的外觀如何? – Kafo

回答

1

好吧我想通了一些想法後。問題是在componentWillMount之前調用render,所以子組件Comments第一次使用初始道具進行渲染,所以我需要讓子組件知道當父組件設置其狀態時它將接收新的道具。我將此代碼添加到了我的子組件:

componentWillReceiveProps: function(newProps){ 
     this.setState({comments: newProps.comments}) 
    }, 
+0

您不應在組件層次結構的兩個不同級別中表示與狀態相同的數據。它應該保持最高水平的狀態,並作爲道具傳遞下去。您的孩子組件應該將此數據稱爲this.props.comments。否則,你有兩個真實的數據來源,這是不是慣用的React。 – John

+1

@John哦,謝謝你,這是一個很棒的觀點,我現在想做一些重構。 –

+0

如果孩子的組成部分有I/O責任,那麼狀態不是必要的,那麼您不等待慢速道具傳球? – Femtosecond