使用onClick事件从Redux商店删除商品时遇到的问题

问题描述:

我希望能够从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); 
     }) 
    } 

...该代码删除循环中的所有项没有任何错误。我怎样才能使用按钮来删除特定的项目?

你真正得到的项目为它被删除?

试试这个在您的按钮你的地图里:

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

啊!错过了,谢谢! – feners

+0

这是否解决了这个问题?如果是这样,请考虑让其他人看到最佳答案并接受答案,即使不是正确答案,也不要害羞地鼓励其他人,但是如果他们提供有用的见解,使您更接近目标。 –

您需要绑定您的处理程序。

constructor(props) { 
    super(props); 
    this.state = {items: this.props.cart,cart: [],total: 0}; 
    this.handleClick = this.handleClick.bind(this); 
} 

https://facebook.github.io/react/docs/handling-events.html