【发布时间】:2021-09-27 19:01:16
【问题描述】:
所以我正在构建一个反应购物车。我能够添加总数量和总价格功能,但无法显示购物车中产品的初始价格和数量。产品是使用 axios 和使用 useState 存储它。
这是代码
const CartPage = (props) => {
const [cartProducts, setCartProducts] = useState([]);
const [totalQuantity,setTotalQuantity] = useState();
const [totalPrice,setTotalPrice] = useState(0);
const [loading,setLoading]= useState(false);
const { enqueueSnackbar,closeSnackbar} = useSnackbar();
const authCtx = useContext(AuthContext)
const token = authCtx.token;
const userId = authCtx.userId;
useEffect(() => {
setLoading(true)
let queryParams = '?auth=' + token + '&orderBy="userId"&equalTo="' + userId + '"';
axiosInstance.get('/Cart.json'+queryParams).then((response) => {
//console.log(response.data);
let fetchProductData = [];
for (let key in response.data) {
fetchProductData.push({
...response.data[key],
productId: key,
});
}
//console.log(fetchProductData);
setCartProducts(fetchProductData);
setLoading(false)
});
},[token,userId]);
这是 totalPrice 和 Total Quantity 功能,它们在递增和递减计数器处理程序中调用
const totalQuantityHandler=()=>{
const totalQuantityCount=cartProducts.reduce((total,product)=>{
return total+product.quantity;
},0)
//console.log(totalQuantityCount)
setTotalQuantity(totalQuantityCount)
//console.log(cartProducts)
}
const totalPriceHandler=()=>{
const totalPriceCount=cartProducts.reduce((total,product)=>{
return total+product.price*product.quantity;
},0)
//console.log(totalPriceCount);
setTotalPrice(totalPriceCount);
}
const incrementCounterHandler = (index) =>{
const updatedCart = [...cartProducts]
updatedCart[index].quantity++
setCartProducts(updatedCart);
totalQuantityHandler();
totalPriceHandler();
//console.log(cartProducts)
}
const decrementCounterHandler=(index)=>{
const updatedCart = [...cartProducts]
updatedCart[index].quantity--
setCartProducts(updatedCart);
totalQuantityHandler();
totalPriceHandler();
}
所以这里是显示总数量和总价格的 JSX 部分代码
<React.Fragment>
{cartProducts.map((product, index) => {
//console.log(product)
return (
<CartCard
key={product.id}
Image={product.productImage}
Title={product.productName}
Price={product.price}
Details={product.productDetails}
removeFromCart={() => removeFromCartHandler("REMOVE",product.productId)}
moveToFavorites={(event)=>moveToFavoritesHandler(event,product)}
Quantity={product.quantity}
incrementCounter={() => incrementCounterHandler(index)}
decrementCounter={() => decrementCounterHandler(index)}
onHandleCallBack={(value) => sizeChangeHandler(value,index)}
/>
);
})}
<Divider style={{ height: "2px", backgroundColor: "#000" }} />
<Box
display="flex"
alignItems="center"
justifyContent="flex-end"
padding="10px"
margin="20px"
marginBottom="0px"
>
<Typography variant="h6">
SubTotal({totalQuantity} Items): Rs.{totalPrice}
</Typography>
</Box>
<ButtonGroup cancelled={()=>cartPageCancelledHandler()} continued={()=>cartPageContinuedHandler()}/>
</React.Fragment>
我尝试了很多东西,但它似乎不起作用。有没有更好的方法来实现它?
【问题讨论】:
-
你能分享你的jsx的html部分吗?
-
除了总数量和价格是派生状态,因此不应存储在状态中,您的实用程序函数对我来说看起来是正确的。问题是什么?什么时候调用这些函数?
-
@Nayanshah 嘿,我已经添加了 JSX 的 HTML 部分,你可以看看!
-
@DrewReese 嘿,这些函数在递增和递减处理函数中被调用,这些函数用于递增/递减数量。所以基本上问题是我从firebase获取产品,我想显示获取的产品数量和这些产品的总价格。我也应该能够增加或减少产品的数量。我已经编辑了问题的代码部分。您可以查看它!
标签: reactjs axios use-effect shopping-cart use-state