[英]React trying to loop through state object
I am currently trying to create a component that onclick of a button gets appended to a parent component of DOM element. 我目前正在尝试创建一个按钮的onclick附加到DOM元素的父组件的组件。 However I am having a problem getting the initial loop working.
但是我在初始循环工作时遇到了问题。 Here is what I am doing,
这是我在做什么,
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 ;
However when I client the button with onAddChild callback on it, I get 但是,当我通过onAddChild回调客户端按钮时,我得到了
Cannot convert undefined or null to object
无法将undefined或null转换为object
why would this be? 为什么会这样?
Here is a link to my test project, 这是我的测试项目的链接,
https://codesandbox.io/s/0qx9w1qrwv https://codesandbox.io/s/0qx9w1qrwv
You are overwriting your state here: 你在这里覆盖你的州:
let invoice = this.state.invoice.items;
this.setState({ invoice : {'id' : 'INV001'} });
after that call your state will be 在那之后,你的州将会是
{ invoice: {'id': 'INV001'} }
and the items property will be gone. 而物品属性将消失。
If you are trying to add an item, something like this would work: 如果您尝试添加项目,这样的事情会起作用:
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 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.