React-Redux的Cart组件添加Remove按钮报product未定义问题
问题修复方案
核心错误点
- 你将删除按钮放在了购物车商品遍历的
map方法外部,无法获取到每个商品的变量,且遍历时你给当前项命名为cart,代码中不存在product变量,直接调用removeCart(product)就会抛出未定义错误 - 你没有通过
this.props调用redux绑定的removeCart方法,直接调用的是导入的原始action方法,没有经过dispatch派发 - 删除按钮应该放在每一行商品的操作列,而不是表格底部,才能对应删除单条商品
- 原生HTML的
class属性在React中要改为className
修正后完整代码
import React, { Component } from "react" import { connect } from "react-redux"; import { Card, CardBody, CardHeader, CardTitle, Row, Col } from "reactstrap" import PanelHeader from "components/PanelHeader/PanelHeader.js" import { addCart } from "../redux/actions"; import { removeCart } from "../redux/actions"; class Cart extends Component { render () { const cart = this.props.cart return ( <> <PanelHeader size="sm" /> <div className="content"> <Row> <Col xs={12}> <Card> <CardHeader> <CardTitle tag="h4">Products List</CardTitle> </CardHeader> <CardBody> <table className="table table-striped table-hover"> <thead> <tr> <th scope="col"><strong>#</strong></th> <th scope="col"><strong>Name</strong></th> <th scope="col"><strong>Code Item</strong></th> <th scope="col"><strong>Quantity</strong></th> <th scope="col"><strong>Price Total</strong></th> {/* 新增操作列 */} <th scope="col"><strong>Operation</strong></th> </tr> </thead> <tbody> {cart.length > 0 && cart.map((product, index) => ( <tr key={product.id}> <th scope="row">{index}</th> <td>{product.title}</td> <td>{product.code}</td> <td>{product.quantity}</td> <td>{product.price}</td> {/* 新增删除按钮 */} <td> <button onClick={() => this.props.removeCart(product)}>Remove</button> </td> </tr>))} </tbody> </table> </CardBody> </Card> </Col> </Row> </div> </> ) } } const mapStateToProps = (state)=> { return { cart: state.cart } } const mapDispatchToProps = (dispatch) => { return { addCart: (product) => {dispatch(addCart(product))}, removeCart: (product) => {dispatch(removeCart(product))} } } export default connect(mapStateToProps, mapDispatchToProps)(Cart);
补充说明
我把遍历的当前项命名改成了product避免和外层的购物车数组cart重名,逻辑更清晰,如果你要保持原来的命名,只要把按钮调用的参数改成对应的cart即可。
内容的提问来源于stack exchange,提问作者Shpongle
相关产品推荐
相关产品推荐

