2017-03-06 106 views
0

我無法顯示數組的狀態以便推送其中的對象。 CreateCards組件在addCart函數中返回良好的信息。未捕獲的類型錯誤:無法讀取未定義的屬性

constructor(){ 
    super(); 
    this.state = { 
     cards: [] 
    } 
} 


addCart(title, qte){ 
    console.log(title); 
    console.log(qte); 
    console.log(this.state.cards); 
    //let array = this.state.cards; 
    //array.push({title: title, qte: qte}); 
} 

render(){ 
    console.log(this.state.string); 
    return (
     <div> 
      <div> 
       <h2>Panier</h2> 

      </div> 
      { 
       data.map((bike, index)=>{ 
        return (
         <CreateCards key={index} title={bike.title} img={bike.img} price={bike.price} addCart={this.addCart}/> 
        ) 
       }) 
      } 
     </div> 
    ) 
} 
+2

你忘了將addCart綁定到組件上。在構造函數中添加'this.addCart = this.addCart.bind(this)',它應該可以工作。 – QoP

+0

'data.map'對我來說沒有任何意義,因爲你沒有在這段代碼中的任何地方聲明變量'data'。這是一個全局變量嗎? – finalfreq

+0

數據在我的文件開始處導入(從'data.js'導入數據) –

回答

-2

您還應該使用 const newCards = this.state.cards.push({title: title, qte: qte}); this.setState({ cards: newCards }); 而不是試圖直接變異狀態對象。

+0

^^因爲您正在使用push,所以也會直接改變狀態對象。你應該使用'concat'而不是返回一個新的數組。 Push也返回數組的長度,所以在你的例子中'newCards'實際上等於一個數字而不是數組。 – finalfreq

+0

是的,沒錯。我的錯。 – Tom

0

你addCart功能應該像

addCart(title, qte){ 
    console.log(title); 
    console.log(qte); 
    const array = this.state.cards.concat({title: title, qte: qte}) 
    this.setState({cards: array}) 
} 

Push方法變異的狀態,所以使用的,而不是它的concat。它返回一個新的數組。

相關問題