2015-07-20 30 views
1

發生UI事件時,我的頂級React組件接收數據以用作外部對象的道具。我想知道更新組件的道具以用於下一個渲染的正確方法。從外部源設置道具

看起來像組件生命週期方法之一應該處理這個問題,但似乎並非如此。

下面的代碼顯示了我試過:

Root.update自定義的方法調用外部一旦數據已準備就緒。顯示的兩種技術都有效。

Root.getDefaultProps用於檢索第一個渲染道具。

Root.render這也適用,但在第一次渲染時是多餘的。

Root.componentWillUpdate不起作用,但似乎應該。

Root.componentWillReceiveProps這對工作沒有意義;道具不會從React組件收到。

var Root = React.createClass({ 

    update: function() { 
    this.setProps(Obj.data); // works but setProps is deprecated 
    this.props = Obj.data; // always works 
    }, 

    getDefaultProps: function() { 
    return Obj.pageload(); // works on first render 
    }, 

    componentWillUpdate: function() { 
    this.props = Obj.data. // does not work 
    this.setProps(Obj.data); // infinite loop 
    }, 

    componentWillReceiveProps: function() { 
    this.props = Obj.data; // does not work 
    }, 

    render: function() { 
    this.props = Obj.data; // works but is redundant 

    // ... 
    }, 
}); 
+0

道具應該是不可變的。你是否可以在你的根組件上使用狀態並將其作爲道具傳遞給子組件? – noveyak

回答

2

在某些時候你必須調用React.render來呈現,最初的根組件與你的道具。

要使用新道具更新組件,只需再次調用React.render即可使用新道具對同一Dom元素上的相同組件進行更新。

這不會重新安裝該組件,但實際上只是將掛載的實例發送給您的新道具,並使其重新渲染。

如果您想控制組件接收道具時發生的情況,請查看組件生命週期方法componentWillReceiveProps

+0

感謝您的回覆;我沒有想過嘗試這個。當我讀到'setProps'文檔的註釋時,我正在考慮在組件上調用'render'與'React.render'。非常有用的知道這樣做並不意味着React必須從頭開始,這正是我所期望的。再次感謝。 – cantera

+0

沒問題。由於該方法的措詞,我認爲這是一個相當普遍的問題;) –