我正在尝试将新项目推送到State array
的{{1}}中,但遇到了一些问题。下面是我的代码。我确定我做错了事
objects
在constructor(props) {
super(props);
this.state = {
bill: []
};
}
componentWillReceiveProps(nextProps, nextState) {
if (nextProps.bills !== this.props.bills) {
let billsObj = nextProps.bills
billsObj.map((billsObj) => {
var joined = this.state.bill.concat({billId:billsObj.id,checked:false});
console.log(joined, "joined", this.state.bill)
this.setState({
bill: [...this.state.bill, ...joined]
}, () => {
console.log(this.state.bill, billsObj.id)
})
})
}
}
中,我得到了componentWillReceiverProps
,然后将其映射为将值推入array
state
中,但是最后,我只得到了一个array,但是array
有11个值,而我的props array
只得到一个值。希望得到一些帮助。
答案 0 :(得分:1)
如果要更新从当前状态派生的状态,则需要考虑以前的状态,这在here中有详细说明。这就是为什么您多次调用setState
最终以状态数组中的最后一个bill
结尾的原因。
如果您将bills
放在一个中间数组中,并且完成后只需setState
一次,它将按预期工作:
componentWillReceiveProps(nextProps, nextState) {
if (nextProps.bills !== this.props.bills) {
const bill = nextProps.bills.map(bill => {
return { billId: bill.id, checked: false };
});
this.setState({ bill });
}
}