在儀表板上工作,當選項更改時更改週期(即Month,Quarter等)時,我需要更新表。遇到綁定問題。ES6 React綁定更改
export default class SalesFinancialDiv extends React.Component {
constructor(props) {
super(props);
this.state = {periods: null, period: null};
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
$.getJSON("/marketing-dashboard/sales-financial/periods", function(result) {
this.setState({periods: result, period: result[1]});
}.bind(this));
}
onChange(event) {
console.log(event.target.value);
this.setState({period: event.target.value});
}
render() {
if(this.state.periods != null && this.state.period != null) {
return (
<div>
<h3>Marketing Dashboard | Financial Data</h3>
<SalesFinancialPeriods periods={this.state.periods} onChange={this.onChange} />
<SalesFinancialTable period={this.state.period} />
</div>
);
} else {
return (
<div>Loading...</div>
);
}
}
}
class SalesFinancialPeriods extends React.Component {
makeOptions(data) {
return (
data.map(function(period) {
return (
<option value={period}>{period}</option>
)
})
);
}
render() {
return (
<div id="sales-financial-periods">
<select onChange={this.props.onChange} >
{this.makeOptions(this.props.periods)}
</select>
</div>
);
}
}
class SalesFinancialTable extends React.Component {
render() {
return (
<table className="table table-striped table-codero">
<TableHeader />
<TableBody period={this.props.period} />
<TableFooter />
</table>
);
}
}
class TableBody extends React.Component {
constructor(props) {
super(props);
this.state = {data: null, dates: null};
}
componentDidMount() {
let url1 = "/marketing-dashboard/sales-financial/data/" + this.props.period;
let url2 = "/marketing-dashboard/sales-financial/dates/" + this.props.period;
$.getJSON(url1, function(result) {
this.setState({data: result});
}.bind(this));
$.getJSON(url2, function(result) {
this.setState({dates: result});
}.bind(this));
}
componentWillReceiveProps(nextProps) {
let url1 = "/marketing-dashboard/sales-financial/data/" + nextProps.period;
let url2 = "/marketing-dashboard/sales-financial/dates/" + nextProps.period;
$.getJSON(url1, function(result) {
this.setState({data: result});
}.bind(this));
$.getJSON(url2, function(result) {
this.setState({dates: result});
}.bind(this));
}
render() {
//
}
}
正如你所看到的最高水平類SalesFinancialDiv
打完並得到periods
和初始period
它然後傳遞期間的SalesFinancialPeriods
類建立下拉。另外,SalesFinancialDiv
將兩個孩子的初始period
傳遞給TableBody
,這會觸發數據以填充表格。
正如我所說的,我需要弄清楚如何將新的選定時間段傳遞給TableBody
類以啓動並獲取新的數據集。
更新改變<select>
到<select onChange={this.props.onChange}>
,我現在看到的父節點的變化,但我沒有看到父節點通過新period
給孩子們。同事和我想,因爲最高級別的節點正在更新w/setState
它會重新呈現兒童。還檢查了是否發送了xhr
請求,而不是。
更新2實施componentWillReceiveProps
並修復問題!由於
這似乎是正確的解決方案。增加了原來的帖子。謝謝@ Kocur4d – Adam
用小ps更新 – Kocur4d
看到了。同事使用它,我一直在研究它。剛剛在2-3周前開始使用React。 – Adam