【问题标题】:Problems deleting items from Redux store using onClick event使用 onClick 事件从 Redux 商店删除项目的问题
【发布时间】:2018-01-14 05:05:51
【问题描述】:

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

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

【问题讨论】:

    标签: javascript html reactjs redux


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

      您真的要删除该项目吗?

      在地图内的按钮上试试这个:

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

      【讨论】:

      • 这解决了问题吗?如果是这样,请考虑为其他人投票以查看最佳和公认的答案,即使不是正确的答案,但如果他们提供了使您更接近目标的有用见解,请不要害羞地为其他人点赞。
      猜你喜欢
      • 2021-06-21
      • 1970-01-01
      • 2013-06-07
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多