繁体   English   中英

使用onClick事件从Redux存储删除项目时出现问题

[英]Problems deleting items from Redux store using onClick event

我希望能够从store的数组中删除特定对象。 我做了一个delete item函数,该函数可以工作并删除对象,但是当我使用随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);
        })
    }

...该代码将删除循环中的所有项目,而不会出现任何错误。 如何使用按钮删除该特定项目?

您需要绑定处理程序。

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

您是否真的要删除该项目?

在地图上的按钮上尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM