【问题标题】:Push items into empty State array of objects将项目推送到空的 State 对象数组中
【发布时间】:2018-12-03 08:20:10
【问题描述】:

我正在尝试将新项目推送到objectsState array,遇到一些问题。下面是我的代码。我确定我出了点问题

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 中获得单个值。希望能得到一些帮助。

【问题讨论】:

  • 你真的需要把你的道具中的bills放在状态吗?你不能直接在 render 的 props 中使用它们吗?
  • 我需要放因为我需要那个状态数组,实际上我想做一个对象数组,我只是在更新我的问题

标签: javascript arrays reactjs react-state-management


【解决方案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 });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2021-11-13
    • 2019-10-01
    • 2019-01-08
    • 2015-09-11
    • 2019-07-20
    相关资源
    最近更新 更多