【问题标题】:TypeError: setCartCount is not a function - React Hooks - ReduxTypeError: setCartCount 不是一个函数 - React Hooks - Redux
【发布时间】: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


    【解决方案1】:

    代替:

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

    你应该有:

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

    应该使用array destructuring 语法。它允许我们为通过调用useState 声明的状态变量赋予不同的名称。这些名称不是useState API 的一部分。

    【讨论】:

    • 哦,哇,我怎么错过了!感谢您的帮助!
    猜你喜欢
    • 2021-07-11
    • 2020-08-18
    • 1970-01-01
    • 2019-04-01
    • 2021-10-11
    • 2018-07-25
    • 2020-07-22
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多