2017-08-06 69 views
0

我希望能夠從store中的陣列中刪除特定對象。我做了一個刪除項目的功能,並刪除對象,但我還沒有能夠弄清楚如何使這個功能的工作,當我使用與每個對象與map呈現的按鈕。這是我的組件:使用onClick事件從Redux商店刪除商品時遇到的問題

import React, { Component } from 'react'; 
import {addCart} from './Shop'; 
import { removeCart } from '../../actions'; 
import { connect } from 'react-redux'; 

export class Cart extends Component { 
    constructor(props) { 
     super(props); 
     this.state = {items: this.props.cart,cart: [],total: 0}; 
    } 

    handleClick(item) { 
     this.props.onCartRemove(item); 
    } 

    ... 


    render() { 
     return(
      <div className= "Webcart" id="Webcart"> 
       <div> 
        {this.state.items.map((item, index) => { 
         return <li className='cartItems' key={'cartItems_'+index}> 
          <h4>{item.item}</h4> 
          <p>Size: {item.size}</p> 
          <p>Price: {item.price}</p> 
          <button onClick={this.handleClick}>Remove</button> 
         </li> 
})} 
       </div> 
       <div>Total: ${this.countTotal()}</div> 
      </div> 
     ); 
    } 
} 

const mapDispatchToProps = (dispatch) => { 
    return { 
     onCartAdd: (cart) => { 
      dispatch(addCart(cart)); 
     }, 
     onCartRemove: (item) => { 
      dispatch(removeCart(item)); 
     }, 
    } 
} 

function mapStateToProps(state) { 
    return { cart: state.cart }; 
} 

export default connect(mapStateToProps, mapDispatchToProps)(Cart); 

使用功能​​我得到Uncaught TypeError: Cannot read property 'props' of null。如果我嘗試類似

deleteItem() { 
     return this.state.items.reduce((acc, item) => { 
      return this.props.onCartRemove(item); 
     }) 
    } 

...該代碼刪除循環中的所有項沒有任何錯誤。我怎樣才能使用按鈕來刪除特定的項目?

回答

1

你真正得到的項目爲它被刪除?

試試這個在您的按鈕你的地圖裏:

<button onClick={() => this.handleClick(item)}>Remove</button> 
+0

啊!錯過了,謝謝! – feners

+0

這是否解決了這個問題?如果是這樣,請考慮讓其他人看到最佳答案並接受答案,即使不是正確答案,也不要害羞地鼓勵其他人,但是如果他們提供有用的見解,使您更接近目標。 –