简体   繁体   English

类型错误:setCartCount 不是 function - React Hooks - Redux

[英]TypeError: setCartCount is not a function - React Hooks - Redux

I am in the process of setting up and implementing redux in my ecommerce project, and currently I am trying to get it set up so the UI updates the BasketBadge I created to display number of items in the cart when an item is added to the cart.我正在我的电子商务项目中设置和实施 redux,目前我正在尝试对其进行设置,以便 UI 更新我创建的 BasketBadge 以在将商品添加到购物车时显示购物车中的商品数量.

I am using redux and react hooks to achieve this, however for some reason I am thrown an error I have not actually had before when using hooks: "TypeError: setCartCount is not a function".我正在使用 redux 和反应钩子来实现这一点,但是由于某种原因,我在使用钩子时抛出了一个我以前实际上没有遇到的错误:“TypeError:setCartCount 不是函数”。

I had a similar error for when I was implementing my addToCart functionality however the workaround for that issue does not work for this one.我在实现 addToCart 功能时遇到了类似的错误,但是该问题的解决方法不适用于此问题。

code is below>代码如下>

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);

Instead of:代替:

const {cartCount, setCartCount} = useState(0);

You should have:你应该有:

const [cartCount, setCartCount] = useState(0);

The array destructuring syntax should be used.应该使用数组解构语法。 It lets us give different names to the state variables we declared by calling useState .它让我们可以为我们通过调用useState声明的 state 变量赋予不同的名称。 These names aren't a part of the useState API.这些名称不是useState API 的一部分。

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

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