2017-07-03 91 views
1

當我點擊按鈕[加入購物車]我收到一個錯誤: enter image description here。 我該如何解決這個問題?
這裏是我的full code link,以下是一個抽象的,是相關的問題:我應該如何解決TypeError的「未定義的屬性」道具?

class ProductsList extends Component { 
    .... 
    renderProductsList() { 
    function mapProductCards(elem) { 
     return (
     <Card className="m-1" style={{width: '18rem'}} key={elem.id}> 
      .... 
      <CardText>isAvailable</CardText> 
      <Button onClick={() => this.props.addItemToCart(elem.id)}>Add to Cart</Button> 
      </CardBlock> 
     </Card> 
    ) 
    } 
.... 
this.props.products .... 
     .map(mapProductCards) 
.... 
const mapDispatchToProps = (dispatch) => ({ 
.... 
    addItemToCart(value) { 
    dispatch(addToCart(value)); 
    } 
.... 
}); 

export default connect(mapStateToProps, mapDispatchToProps)(ProductsList); 
.... 
+0

嘗試將其存儲到那個(that = this),並在map函數(that.props ... map())中使用它。 – Nithesh

+0

'renderProductsList'是一個功能組件? –

+0

不,這是一個功能。我會在我的問題 –

回答

1

在你renderProductsList函數的開始,你this變量分配給當地的一個。像這樣:

renderProductsList() { 
    var that = this; 
    function mapProductCards(elem) { 
    return (

然後在需要的地方使用that。例如,你的按鈕現在會是:

<Button onClick={() => that.props.addItemToCart(elem.id)}>Add to Cart</Button> 

或者,使用箭頭函數。像這樣:

renderProductsList() { 
    mapProductCards = (elem) => { 
    return (

這將保留對您實際需要的對象的參考this


編輯

看着你完整的代碼,根據您如何使用您的mapProductCards功能後,您需要在正確的對象this使用通過。您可以將該對象作爲第二個參數傳遞給您的map。就像這樣:

this.props.products.map(mapProductCards, this); 

您可能會發現map()的文檔超過在MDN有趣:

var new_array = arr.map(function callback(currentValue, index, array) { 
    // Return element for new_array 
}[, thisArg]) 

thisArg: Optional. Value to use as this when executing callback.

+0

中添加一個鏈接到完整的代碼,對不起,但它沒有幫助。順便說一句,我正在使用「babel-plugin-transform-class-properties」插件,這使得我自動綁定。但無論如何,我改變這一點像你說的那樣,但仍然是一個錯誤。以下是http://imgur.com/DJneu5n錯誤的截圖。 –

+0

@TarasYaremkiv好吧。你在哪一行得到錯誤?它仍然是同一個地方嗎?那個錯誤意味着'this'沒有'props'屬性,所以它應該是相關的。 – Chris

+0

我收到來自proptypes的錯誤。 「171:18錯誤'addItemToCart'PropType被定義,但prop永遠不會被使用react/no-unused-prop-types」。對不起,這不是同一個錯誤 –

1

我也面臨這個問題,問題是,當我調試我的代碼,當地這即此對象該函數給出了未定義的對象。你需要實例化該函數的這個對象addItemToCart,因爲當你點擊按鈕時,它會給你一個控制檯上的錯誤,說

你的方法addItemToCart未定義 克服這一點,你需要定義本地以此爲

 renderProductsList() { 
     var localThis= this; 
} 

,然後打電話給你的方法

onClick={() => localThis.props.addItemToCart(elem.id)} 

如果您使用的是循環中的功能說的地圖,則你需要做的

this.state.map(function(){ 


},**this**) 

保持這種

+0

抱歉,但它並沒有幫助。順便說一句,我正在使用「babel-plugin-transform-class-properties」插件,這使得我自動綁定。這裏有一個錯誤http://imgur.com/DJneu5n。 –

+0

的屏幕截圖無法打開你的image.restricted在office.can你請告訴錯誤? –

+0

你可以檢查是否console.log(這)insode你函數renderProductsList給定了undefined或者沒有? –

相關問題