【发布时间】:2016-08-26 22:40:53
【问题描述】:
我正在尝试创建两个表,我可以在其中将数据提取到父组件中,将数据传递到一个表中,并允许将数据从一个表移动到另一个表。所以我需要能够为所有 AJAX 数据创建一个表,然后为 Selected 数据创建一个表。我无法通过道具传递数据,因为一旦 AJAX 请求完成,孩子就不会更新。 (基本上父组件观察并在两个子组件之间共享数据。)
我已经尝试过文档中的“WillReceive”和“WillUpdate”样式方法,但它们从未被调用,我尝试更新状态
这是请求(我现在正在伪造数据)
getInvoiceData(){
return new Promise(function(resolve, reject) {
console.log("hi");
resolve([{number: "1"},{number: "2"},{number: "3"}]);
})
}
这里是我使用req的地方
componentDidMount() {
const self = this;
self.getInvoiceData()
.then((response) => {
self.state.invoices = response;
console.log(self.state);
})
.catch((err) => {
console.error(err);
})
}
这是我的渲染
render () {
return (
<div>
<p>Selected:
{
function() {return JSON.parse(this.selected)}
}
</p>
<InvoicePickTable invoices = {this.state.invoices} selected = {this.selected} />
<button>Move</button>
<InvoiceSelectedTable selectedInvoices = {this.state.selectedInvoices} />
</div>
);
}
这是我的孩子
import React from 'react';
class InvoicePickTable extends React.Component {
constructor(props) {
console.log("constructor called");
super(props);
this.state = {invoices: []};
}
selectInvoice(invoice) {
this.props.selected = invoice;
}
//never gets called
componentWillUpdate(nextProps, nextState) {
console.log(nextProps);
console.log(nextState)
console.log("eyy lmao");
this.state.invoices = nextProps.invoices;
this.state.hasDate = true;
}
//never gets called
componentWillReceiveProps(nextProps) {
console.log(nextProps);
console.log("eyy lrofl");
this.state.invoices = nextProps.invoices;
}
render() {
return (
<table>
<thead>
<tr>
<th>Invoice #</th>
<th>Task Price</th>
<th>Balance</th>
<th>Task Name</th>
<th><button onClick={()=>{console.log(this.props);console.log(this.state)}}>props</button></th>
</tr>
</thead>
<tbody>
{
this.props.invoices.map(function (invoice) {
console.log("in");
console.log(invoice);
return (
<tr key = {invoice.number} onClick={this.selectInvoice(invoice)}>
<td>{invoice.number}</td>
</tr>
);
})
}
</tbody>
</table>
);
}
}
export default InvoicePickTable;
【问题讨论】: