0
我有兩個反應類應該建立一個表,它計算各種屬性的總計。反應渲染不按順序執行
在我的主類,我有:
const TableComponent = React.createClass({
resetRowTotals: function() {
console.log("Resetting");
this.total1 = 0;
this.total2 = 0;
this.total3 = 0;
this.total4 = new Set();
},
addToRowTotals: function(total1, total2, total3, total4) {
console.log("Updating");
this.total1 += ...;
this.total2 += ...;
this.total3 += ...;
this.total4.add(...);
},
render: function() {
this.resetRowTotals();
this.tableRows = this.props.items.map(item => React.createElement(TableRow, {..., addToRowTotals: this.addToRowTotals}));
console.log(this.total1, this.total2, this.total3, this.total4);
return React.createElement("table", {id: "..."},
React.createElement("thead", {},
React.createElement("tr", {},
React.createElement("th", {}, ...),
React.createElement("th", {}, ...),
React.createElement("th", {}, ...),
React.createElement("th", {}, ...),
React.createElement("th", {}, ...)
)
),
React.createElement("tbody", {},
React.createElement("tr", {},
React.createElement("td", {}, ...),
React.createElement("td", {}, ...),
React.createElement("td", {}, ...),
React.createElement("td", {}, ...),
React.createElement("td", {}, ...)
),
this.tableRows
)
)
}
});
而對於我行組件我有:
const TableRow = React.createClass({
getVal2: function() {...},
getVal3: function() {...},
getVal4: function() {...},
render: function() {
let val1 = this.props....;
let val2 = this.getVal2();
let val3 = this.getVal3();
let val4 = this.getVal4();
this.props.addToRowTotals(val1, val2, val3, val4);
return React.createElement("tr", {},
React.createElement("td", {}, this.props....),
React.createElement("td", {}, val1),
React.createElement("td", {}, val2),
React.createElement("td", {}, val3),
React.createElement("td", {}, val4)
)
}
});
然而,當我看看是可以獲得表創建,所有錶行都很好,但總行(位於表頂部)顯示全部爲0
當我查看控制檯以查看我的函數的執行順序時,我看到:
Resetting
0 0 0 Set(0) {}
Updating
我想到:
Resetting
Updating
(total1's value) (total2's value) (total3's value) Set(x) {(total4 values)}
它不會出現該代碼是爲了得到執行。
總計應該被重置,然後主要行被創建,它調用addToRowTotals函數,然後只是爲了確保總計數據是正確的,我記錄所有4個總值。
爲什麼在我創建表格行之前,控制檯正在記錄總值?
實際上,這聽起來對我來說聽起來不對 - 你可以先嚐試簡單地將'addToRowTotals'綁定到主要元素嗎?基本上,你傳遞給'TableRow'組件的元素(在map調用中)應該看起來像這樣:'{...,addToRowTotals:this.addToRowTotals.bind(this)}' – iceman
另外,我認爲這是使用組件狀態會更有意義 – iceman
綁定addToRowTotals似乎不會以任何可感知的方式影響功能。 我認爲你對於存儲val#變量的位置是非常正確的。這只是一個恥辱,因爲我希望組件彼此獨立(但讓孩子仍然可以用新數據調用特定的父功能)。 在我這樣做之前,我嘗試使用componentWillUpdate(nextProps,nextState)來計算值並在渲染髮生之前將它們傳遞給父項,但這隻會使代碼更加不可靠和不可用。 – S0rn