2015-12-28 55 views
0

我建立一个应用程序来学习反应,现在用火力地堡作为我的数据存储。我已将我的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 
    }); 
    }, 

回答

1

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

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

啊当然,我设置addExpenditure但没有更新removeExpenditure。在补充中,我使用了:'cashbook:{支出:this.state.cashbook.expenditure}'。这是否更有效率,因为州内还有一个收入对象? – zeKoko

+0

啊,所以你只要想重置状态?你可以做,通过做'this.replaceState(this.getInitialState())' –

+0

辉煌,谢谢:) – zeKoko

相关问题