我正在开发一个学习 React 的应用程序,用户可以在其中记录他们的月收入、账单和交易。State 有一个名为 cashbook
的对象,其中包含 3 个嵌套对象 ( income: {}, expenditure: {}, transactions: {}
)
getInitialState() {
return {
cashbook: {
expenditure: {},
income: {},
transactions: {}
}
}
}
我根据Firebase中定义的每个对象,让这一切运行良好。我现在正在尝试使其工作,以便该应用程序仍然可以在 Firebase 未定义所有对象的情况下运行。(我描述得很糟糕,不是吗?因此,假设用户在状态中的每个对象中都有数据,然后从支出中删除所有数据,应用会出错,因为它尝试从支出状态对象输出数据,但删除所有项目会完全删除 Firebase 中的对象,因此App
状态。(我正在使用泰勒·麦金尼斯的变基(https://github.com/tylermcginnis/re-base)
以下是应用程序的渲染,组件DidMount和Spending的渲染方法,可能会更好地解释它。
(错误与 Expenditure
React 类中的这一行有关:{Object.keys(this.props.cashbook).map(this.renderExpenditure)}
,错误为:
未捕获的类型错误:无法将未定义或 null 转换为对象
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>
);
}
});
和支出:
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>
);
}
});
排序 - 我最终使用了:
{Object.keys(this.props.cashbook || {}).map(this.renderExpenditure)}
这确保了如果现金簿对象中没有任何内容,则使用空对象。