我正在构建一个应用程序来学习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: {}
}
}
渲染项目并尝试删除它们的功能如下:
(任何人都可以看到我做错了什么,或者这个代码太少而无法解决发生的事情?)
提前致谢。
在App
中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
});
},
答案 0 :(得分:1)
您在setState中设置了错误的值。支出在根状态中不存在,因此您必须覆盖包含它的父级。它应该是:
this.state.cashbook.expenditure[key] = null;
this.setState({
cashbook: this.state.cashbook
});