我正在尝试制作一个简单的购物车计数器,但收到此错误。我对mapStateToDispatch是否正常工作感到困惑。导入了所有模块,功能正常,但是当我单击添加,删除按钮时仅出现此错误
import React,{Component} from 'react';
import './cart.css';
import {product,product1} from './product.js'
import 'bootstrap/dist/css/bootstrap.min.css';
import {incrementCount , decrementCount} from './actions/buttonBehave';
import {connect} from 'react-redux';
import { bindActionCreators } from 'redux'
export class Cart extends Component{
state = {
buttonClicked : false
}
handleButton= () =>{
this.setState({
buttonClicked : true
})
}
render()
{
return(
<div className="cardDiv">
<div className="card" >
<img className="card-img-top" src={product.image} alt="Card image" height="350px" />
<div className="card-body">
<h4 className="card-title">{product.name}</h4>
<p className="card-text">Model : {product.modelName}</p>
<p className="card-text">Price : {product.price}</p>
<a href="#" className="btn btn-primary " onClick={this.handleButton.bind(this)}> {this.state.buttonClicked ? "Add another" : "Add to cart"} </a>
<p className="card-text">Added : {this.props.count}</p>
<button onClick = { () => this.props.incrementCount ()}>Remove</button>
<button onClick = { () => this.props.decrementCount()}>ADD</button>
<p className="card-text">{this.props.count}</p>
</div>
</div>
</div>
);
}
}
const mapStateToProps= (state) =>{
return{
count : state.count
}
}
const mapDispatchToProps = () => {
return {
incrementCount,
decrementCount
}
}
export default connect(mapStateToProps,mapDispatchToProps())(Cart);
答案 0 :(得分:3)
您正在调用该函数,而不是传递其引用
export default connect(mapStateToProps,mapDispatchToProps())(Cart);
// ------------------------------------------------------^^--------
更改为此
export default connect(mapStateToProps, mapDispatchToProps)(Cart);
另一种选择是根本不使用mapDispatchToProps
并使用您所连接的组件收到的分派
export default connect(mapStateToProps)(Cart);
然后使用分派
this.props.dispatch(decrementCount())