React trying to loop through state object

时间:2017-10-12 09:56:04

标签: javascript reactjs

I am currently trying to create a component that onclick of a button gets appended to a parent component of DOM element. 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

Cannot convert undefined or null to object

why would this be?

Here is a link to my test project,

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

1 个答案:

答案 0 :(得分:2)

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 });