我希望能够从store
中的数组中删除特定对象。我创建了一个删除项功能,可以工作和删除对象,但是当我使用每个带有map
的对象渲染的按钮时,我还无法弄清楚如何使这个功能正常工作。这是我的组成部分:
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);
使用handleClick
函数,我得到Uncaught TypeError: Cannot read property 'props' of null
。如果我尝试像
deleteItem() {
return this.state.items.reduce((acc, item) => {
return this.props.onCartRemove(item);
})
}
...代码删除循环中的所有项目,没有任何错误。如何使用该按钮删除该特定项目?
答案 0 :(得分:1)
你需要绑定你的处理程序。
constructor(props) {
super(props);
this.state = {items: this.props.cart,cart: [],total: 0};
this.handleClick = this.handleClick.bind(this);
}
答案 1 :(得分:1)
你真的得到要删除它的物品吗?
在地图内的按钮上尝试此操作:
<button onClick={() => this.handleClick(item)}>Remove</button>