0

我正在尝试将新项目推入State arrayof 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,但最后我在数组中只得到一个值,但props array有 11 个值,我只在我的state array. 希望能得到一些帮助。

4

1 回答 1

1

如果要更新从当前状态派生的状态,则需要考虑以前的状态,此处详细说明。这就是为什么您的多次调用只以状态数组中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 });
  }
}
于 2018-06-24T17:19:07.263 回答