gpt4 book ai didi

javascript - React 试图循环遍历状态对象

转载 作者:行者123 更新时间:2023-11-29 11:01:17 29 4
gpt4 key购买 nike

我目前正在尝试创建一个组件,将按钮的点击附加到 DOM 元素的父组件。但是我在使初始循环工作时遇到问题。这是我正在做的,

 class GenerateInvoice extends Component {

constructor(props) {
super(props);
this.state = {
'invoice': {
'items' : {}
}
};

this.onAddChild = this.onAddChild.bind(this);
}

render() {
const children = [];
for (var i = 0; i < Object.keys(this.state.invoice.items); i += 1) {
children.push(<InvoiceItemForm key={i} number={i} />);
};
return(
<div>
<a href="" onClick={this.onAddChild}>Add New Item</a>
{children}
</div>
)
}

onAddChild = (e) => {

e.preventDefault();
let invoice = this.state.invoice.items;
this.setState({ invoice : {'id' : 'INV001'} });
}


}

export default GenerateInvoice ;

然而,当我使用 onAddChild 回调客户端时,我得到了

Cannot convert undefined or null to object

为什么会这样?

这是我的测试项目的链接,

https://codesandbox.io/s/0qx9w1qrwv

最佳答案

你在这里覆盖了你的状态:

let invoice = this.state.invoice.items;
this.setState({ invoice : {'id' : 'INV001'} });

在那之后你的状态将是

{ invoice: {'id': 'INV001'} }

并且 items 属性将消失。

如果你想添加一个项目,像这样的东西会起作用:

let invoice = this.state.invoice;
// creates an updated version of the items without changing the original value
let updatedItems = invoice.items.concat({'id': 'INV001'});
// creates a new version of the invoice with the updated items
let updateInvoice = { ...invoice, items: updatedItems };
// update the invoice on the state to the new version
this.setState({ invoice });

关于javascript - React 试图循环遍历状态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46706630/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com