将项目推入对象的空状态数组

时间:2018-06-24 16:39:38

标签: javascript arrays reactjs react-state-management

我正在尝试将新项目推送到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只得到一个值。希望得到一些帮助。

1 个答案:

答案 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 });
  }
}