我正试着把新东西塞进 State array 属于 objects ,面临一些问题。下面是我的代码。我肯定我做错了
State array
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 阵列 ,但最后我只得到数组中的一个值,但是 props array 有11个值,我的 state array . 希望能得到帮助。
componentWillReceiverProps
array
state
阵列
props array
state array
如果要更新从当前状态派生的状态,则需要考虑以前的状态,下面将详细说明 here 是的。这就是为什么你多次打电话给 setState 最后一个就结束了 bill 在你的状态数组中。
setState
bill
如果你保持 bills 在中间数组中, 设置状态 一旦完成:
bills
设置状态
componentWillReceiveProps(nextProps, nextState) { if (nextProps.bills !== this.props.bills) { const bill = nextProps.bills.map(bill => { return { billId: bill.id, checked: false }; }); this.setState({ bill }); } }