發生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
// ...
},
});
道具應該是不可變的。你是否可以在你的根組件上使用狀態並將其作爲道具傳遞給子組件? – noveyak