【发布时间】:2021-04-16 15:46:00
【问题描述】:
我正在我的电子商务项目中设置和实施 redux,目前我正在尝试设置它,以便 UI 更新我创建的 BasketBadge 以在添加商品时显示购物车中的商品数量到购物车。
我正在使用 redux 和 react 钩子来实现这一点,但是由于某种原因,我在使用钩子时抛出了一个我以前实际上没有遇到过的错误:“TypeError: setCartCount is not a function”。
我在实现 addToCart 功能时遇到了类似的错误,但是该问题的解决方法不适用于此问题。
代码如下>
import React, {useState, useEffect} from 'react';
import 'antd/dist/antd.css';
import { Avatar, Badge } from 'antd';
import { ShoppingCartOutlined, UserOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
const BasketBadge = ({cart}) => {
const {cartCount, setCartCount} = useState(0);
useEffect(() => {
let count = 0;
//loop through cart array
// counts all of qty of each item added to populate count
cart.forEach((item) => {
count += item.qty;
});
//once loop is done we set cartCount to new value of count
setCartCount(count);
},[cart, cartCount]);
return(
<div>
<span className="avatar-item">
<Badge count={cartCount}>
<Avatar shape="circle" icon={<ShoppingCartOutlined />} />
</Badge>
</span>
</div>
)
}
const mapStateToProps = (state) => {
return{
cart: state.shop.cart,
}
}
export default connect(mapStateToProps)(BasketBadge);
【问题讨论】:
标签: javascript reactjs redux react-redux react-hooks