我正在开发一个应用程序来学习React,用户可以记录他们的月收入,账单和交易。
State有一个名为cashbook
的对象,包含3个嵌套对象(income: {}, expenditure: {}, transactions: {}
)
getInitialState() {
return {
cashbook: {
expenditure: {},
income: {},
transactions: {}
}
}
}
我根据Firebase中定义的每个对象完成了所有工作。我现在正在尝试使其工作,以便应用程序仍然可以使用Firebase,而不是定义所有对象。 (我描述的非常糟糕,不是吗?)。
因此,假设用户在状态中的每个对象中都有数据,然后从支出中删除所有数据,应用程序错误,因为它试图从支出状态对象输出数据,但删除所有项目会在Firebase中完全删除对象,因此App
州。Expenditure
。 (我正在使用Tyler McGinnis' rebase(https://github.com/tylermcginnis/re-base)
以下是App的渲染,componentDidMount和Expenditure的渲染方法,可以更好地解释它。
(该错误与{Object.keys(this.props.cashbook).map(this.renderExpenditure)}
React类中的此行有关:const App = React.createClass({
getInitialState() {
return {
cashbook: {
expenditure: {},
income: {},
transactions: {}
}
}
},
componentDidMount() {
base.syncState('cashbook', {
context: this,
state: 'cashbook'
});
},
removeCashflow(key, type) {
this.state.cashbook[type][key] = null;
this.setState({
cashbook: { [type]: this.state.cashbook[type] }
});
},
render() {
return(
<div className="cashbook">
<a className="button" onClick={this.LoadSampleData}>Load Sample Data</a>
<Expenditure
cashbook={this.state.cashbook.expenditure}
removeCashflow={this.removeCashflow} />
</div>
);
}
});
,错误内容为:
未捕获的TypeError:无法将undefined或null转换为对象
const Expenditure = React.createClass({
renderExpenditure(key) {
const details = this.props.cashbook[key];
return(
<tr className="item" key={key}>
<td><strong>{details.name}</strong></td>
<td><strong>{h.formatPrice(details.amount)}</strong></td>
<td>{details.category}</td>
<td>{details.type}</td>
<td>{details.date}</td>
<td><button className="remove-item" onClick={this.props.removeCashflow.bind(null, key, 'expenditure')}>Remove</button></td>
</tr>
);
},
render() {
return(
<div className="expenditure">
<table id="exp-table">
<tbody>
{Object.keys(this.props.cashbook).map(this.renderExpenditure)}
</tbody>
</table>
</div>
);
}
});
和支出:
{{1}}
答案 0 :(得分:0)
排序 - 我最终使用:
{Object.keys(this.props.cashbook || {}).map(this.renderExpenditure)}
这确保了如果现金簿对象中没有任何内容,则使用空对象。