使用React删除Firebase中的项,重新渲染会返回未定义的项

Removing item in Firebase with React, re-render returns item undefined

本文关键字:新渲染 返回 未定义 Firebase React 使用 删除      更新时间:2023-09-26

我正在构建一个学习React的应用程序,并使用Firebase作为我的数据存储。我有我的firebase渲染中的所有项目,并且正在尝试删除单个项目。然而,当我尝试删除时,点击删除按钮后,我得到了Uncaught TypeError: Cannot read property 'name' of null,它指的是renderExpenditure函数中的这行代码:

<strong>{details.name}</strong>, <strong>{h.formatPrice(details.amount)}</strong>, {details.category}, {details.type}, {details.date}

状态设置如下:

getInitialState: function() {
    return {
      cashbook: {
        expenditure: {},
        income: {}
      },
      totals: {},
      available: {}
    }
  }

呈现项目并尝试删除它们的功能如下:

(有人能看到我做错了什么吗?还是这段代码太少,无法计算出发生了什么?)

提前谢谢。

在应用程序内

render: function() {
    return(
      <div className="cashbook">
        <div className="expenditure">
          <ul className="items">
            {Object.keys(this.state.cashbook.expenditure).map(this.renderExpenditure)}
          </ul>
        </div>     
      </div>
    );
  }
renderExpenditure: function(key) {
    var details = this.state.cashbook.expenditure[key];
    return(
      <li className="item" key={key}>
        <strong>{details.name}</strong>, <strong>{h.formatPrice(details.amount)}</strong>, {details.category}, {details.type}, {details.date}
        <button className="remove-item" onClick={this.removeExpenditure.bind(null, key)}>Remove</button>
      </li>
    );
  },
removeExpenditure: function(key) {
    this.state.cashbook.expenditure[key] = null;
    this.setState({
      expenditure: this.state.cashbook.expenditure
    });
  },

您在setState中设置了错误的值。支出不存在于根状态,因此必须覆盖包含它的父级。它应该是:

this.state.cashbook.expenditure[key] = null;
this.setState({
  cashbook: this.state.cashbook
});