我正在尝试创建两个表,我可以将数据拉入父组件,将数据传递到一个表中,并允许将数据从一个表移动到另一个表。因此,我需要能够为所有AJAX数据创建一个表,然后为选定数据创建一个表。我无法通过道具传递数据,因为一旦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;
答案 0 :(得分:0)
诀窍不是直接操纵父级中的状态,而是使用setState({})函数。
答案 1 :(得分:0)
要更新状态,您必须使用setState()
功能,请尝试以下操作:
componentDidMount() {
const self = this;
self.getInvoiceData()
.then((response) => {
this.setState({
invoices : response
});
})
.catch((err) => {
console.error(err);
})
}