我正在尝试将事务添加到 React 中的应用程序,并且我想按年、然后按月组织这些事务,因此结构如下:
{
"2016" : {
"january": {
"transaction1": transaction,
"transaction2": transaction,
"transaction3": transaction
},
"february" : {
"transaction1": transaction,
"transaction2": transaction,
"transaction3": transaction
}
}
}
我的应用程序中有一个函数可以接收交易对象,然后我想将其添加到相关年份/月份的交易状态中。
addTransaction(transaction) {
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var year = (new Date()).getFullYear();
var month = monthNames[(new Date()).getMonth()];
console.log(
this.state.transactions != null;
);
// check year exists?
// add if necessary
// check month exists?
// add if necessary
}
我正在努力解决的是:
- 如何查询
transactions
状态对象中是否存在年份 - 然后我需要将其应用到正确的年份和月份(如果确实存在),或者
- 如果没有,请添加新的年份和月份
更新:
我已更新 addTransaction
,并尝试创建年份(尚未添加月份),然后将交易添加到其中,但它没有创建年份,并且我收到 Uncaught TypeError : 无法设置未定义的属性“transaction-1453842528740”
addTransaction(transaction) {
var timestamp = (new Date()).getTime();
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var year = (new Date()).getFullYear();
var month = monthNames[(new Date()).getMonth()];
if (year in this.state.transactions) {
// add to year
} else {
this.state.transactions[year]['transaction-' + timestamp] = transaction;
}
this.setState({
transactions: { [year]: this.state.transactions[year] }
});
}
提前致谢。
最佳答案
如果您喜欢改变对象,则可以这样做:
const transactions = this.state.transactions;
// get or create the year object
const yearObject = transactions[year] || (transactions[year] = {});
// get or create the month object
const monthObject = yearObject[month] || (yearObject[month] = {});
// add the transaction
const transactionId = `transaction-${timestamp}`;
monthObject[transactionId] = transaction;
this.setState({ transactions });
这就是您以不可变风格执行此操作的方式(这将使您的组件变得纯净:
const transactions = this.state.transactions;
// get or create the year object
const yearObject = transactions[year] || {};
// get or create the month object
const monthObject = yearObject[month] || {};
// add the transaction
const transactionId = `transaction-${timestamp}`;
const newTransactions = {
// copy the old object
...transactions,
// assign a copy of the year object
[year]: {
// copy the old year object
...yearObject,
// assign a copy of the month object
[month]: {
// copy the old month object
...monthObject,
// add the new transaction
[transactionId]: transaction
}
}
};
// assign our new object
this.setState({ transactions: newTransactions });
关于javascript - React中查询状态,如果存在则setState或update,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003683/