我的英语说得不太好,但我会尝试一下。
我已经寻找这个有一段时间了,但找不到明确的解决方案,我正在使用 React Hook 进行电子商务,并且在我的全局商店中列出了我的购物车中的产品。
我需要计算产品数量以显示总数量,如何运行我的产品列表的“.reduce”?
是否有必要创建一个useState?
我的购物车的产品列表,它有这个架构
[{
id: 5,
quantity: 3
},{
id: 23,
quantity: 1
}]
我想到了以下几种方式
选项 1:(没有 useState,它有效吗?)
import React from 'react';
import { useSelector } from 'react-redux';
const Cart = () => {
const cart = useSelector((state) => state.myCart); // list cart
const count = cart.reduce((total, product) => {
return total + product.quantity;
}, 0);
return (
<div>
<span>{count}</span>
</div>
);
};
export default Cart;
选项 2:此选项在显示计数时有一点延迟
import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
const Cart = () => {
const cart = useSelector((state) => state.myCart); // list cart
const [count, setCount] = useState(0)
useEffect(() => {
setCount(cart.reduce((total, product) => {
return total + product.quantity;
}, 0));
}, [cart])
return (
<div>
<span>{count}</span>
</div>
);
};
export default Cart;
最好的方法是什么?
谢谢。
最佳答案
如果您只显示计数,您还可以将减少量移至选择器函数回调中。选择器允许您返回状态,但组件会使用它。
import React from "react";
import { useSelector } from "react-redux";
const cartCountSelector = state =>
state.myCart.reduce((total, product) => {
return total + product.quantity;
}, 0);
const Cart = () => {
const count = useSelector(cartCountSelector); // list cart count
return (
<div>
<span>{count}</span>
</div>
);
};
export default Cart;
关于javascript - "Reduce"在使用选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61004286/