2017-10-12 39 views
3

我目前正在嘗試創建一個按鈕onclick被附加到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回調的按鈕,我得到

無法轉換未定義或爲空反對

爲什麼會這樣是?

這裏是我的測試項目中的鏈接,

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

+0

你的狀態對象鍵不必是字符串 –

+1

@KarlTaylor:他們不是。 *屬性名*以字符串形式給出,true,這是可選的,但是無害的。 –

+0

請使用Stack Snippets('[<>]'工具欄按鈕)使用** runnable ** [mcve]更新您的問題。 Stack Snippets支持React,包括JSX; [這是如何做一個](http://meta.stackoverflow.com/questions/338537/)。 –

回答

2

您在這裏覆蓋的狀態:

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

後打電話給你的狀態會

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

物品屬性將會消失。

如果你想添加一個項目,像這樣的工作:

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

這是假設項目被更改爲數組T.J. Crowgers建議上面 – wgcrouch

+0

更改爲數組,它工作的很棒:),但我想要一些關於爲什麼我的循環效率低下的輸入? – Udders