javascript 如何在购物车中填充商品?

hujrc8aj  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(84)

我目前正试图建立一个电子商务网站,遇到了一些问题。主要的一个是,我可以得到当前的项目,将出售出售,但当我把它们添加到购物车,它得到的保存状态,使用户不会失去他们的项目,这是通过一个徽章显示给客户。我被如何填充购物车中的选定项目卡住了。第二个更小的问题是如何处理购物车,如果它低于0目前它填充一个负数我曾试图禁用按钮,如果它低于一个或如果它是在0,但我目前决定切换重点放在显示您添加到购物车的项目列表.下面是显示项目的产品页面的代码

import React from "react";
import RemoveIcon from '@mui/icons-material/Remove';
import AddIcon from '@mui/icons-material/Add';
import Stack from '@mui/material/Stack';
import Badge from '@mui/material/Badge';
import { useEffect, useState } from "react";
import  stockmug from '../images/stockmug.jpg'
import ShoppingCartWidgit from './ShoppingCart'
import Swing from '../images/Swing-Stock-Photo.jpg'
import fork from '../images/fork-spoon.jpg'
import products  from "./product";
import ShoppingCartCheckoutIcon from '@mui/icons-material/ShoppingCartCheckout';
import { makeStyles } from "@material-ui/core/styles";
import {
  Grid,
  Card,
  CardContent,Button,
  Typography,
  CardHeader,CardMedia,
} from "@material-ui/core/";
const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    padding: theme.spacing(2)
  },
  cards: {
    marginTop: theme.spacing(2)
  }
}));
export default function AltCard() {
    const [itemCount, setItemCount] = useState(() => {
        // getting stored value
        const saved = localStorage.getItem("itemCount");
        const initialValue = JSON.parse(saved);
        return initialValue || "";
      });
      function functionToExecute(){

        if(Math.sign(itemCount)!=1){document.getElementById("RemoveFromCart").disabled = true;
    } };

useEffect(() => {
    // storing item count
    localStorage.setItem("itemCount", JSON.stringify(itemCount));
  }, [itemCount])
    // getting stored value
  const classes = useStyles();
// ],   
// id for proucts
//  cart added here
  return (
    <>  <div className={classes.root}>
          <Grid
              container
              spacing={2}
              direction="row"
              justify="flex-start"
              alignItems="flex-start"
          >
              {/* <Grid item xs={12}> */}
              {products.map((elem) => (
                  <Grid
                      item
                      xs={6}
                      className={classes.cards}
                      key={products.indexOf(elem)}
                  >
                      <Card>
                          <CardHeader
                              title={` ${elem.Title}`}
                              subheader={`price: $  ${elem.price}`} />
                          <CardMedia
                              component="img"
                              alt="a litter of puppies inside their doggie bed"
                              height="140"
                              image={` ${elem.imageId}`} />
                          <CardContent>
                              <Typography  
                              description={` ${elem.description}`}
 variant="h5" gutterBottom>
                                  A mug made by Kenais house
                                  <Stack direction="row" spacing={2}>
                                      <Button 
                                        value={itemCount}
                                        onChange={(e) => setItemCount (e.target.value)}
                                      
                                      
                                      onClick={() => {

                                    //  increase the ammount of the counter by one and add to local storage
                                    setItemCount ( itemCount + 1)
                                                                         
                                    ;}
                                 }
                                         size="large" variant="contained" endIcon={<AddIcon />}>
                                          Add To  Cart
                                      </Button>
                                      <Button id="RemoveFromCart" onClick={() => {
                                          functionToExecute();
                                          setItemCount(itemCount - 1);
                                      } } size="large" variant="contained" endIcon={<RemoveIcon />}>
                                          Remove From  Cart
                                      </Button>
                                  </Stack>
                              </Typography>
                          </CardContent>
                      </Card>
                  </Grid>
              ))}
              {/* </Grid> */}
          </Grid>
      </div>
      <Badge badgeContent={itemCount} color="primary">
              <ShoppingCartCheckoutIcon  size="large"color="action" />
          </Badge></>

  );
}
Below is the current page where I am trying to get the items in the cart that were stored in state to appear but I can't figure it out.

这是结帐页面,我想在购物车中选择的项目显示出来

import React, {useEffect,useState} from "react";
import { products } from "./product";

function CheckOut() {
      const [itemCount, setItemCount] = useState(() => {
        // getting stored value
        const saved = localStorage.getItem("itemCount");
        const initialValue = JSON.parse(saved);
        return initialValue || "";
      });
      
   
    return (

  <>
  <div class="row g-0">
  {products.map((product) => {
if (itemCount) [products.id] != 0 
    return  <itemCount ={products}/>
}
  }
)
}
    
  
   <p> check out page</p>
      </div>
    </>
    )
  }
  export default CheckOut;

我试图通过Map上的项目添加到购物车中所示的退房页面,但我一直无法得到任何结果。
我也被显示为负值的下降按钮卡住了。我尝试添加min=0值,但没有帮助

rryofs0p

rryofs0p1#

我注意到一些事情
1.您可以使用函数作为初始值,但默认返回值应该是0而不是"",并确保您从localStorage获得的初始值是number而不是string。您可能需要使用parseInt。我不认为这是一个好主意,使用本地存储为您的情况。考虑使用一些状态管理库,如recoilRedux
1.当你只想增加值时,使用prev value,而不是state value。比如说,这样做

onClick={() => {
    // increase the ammount of the counter by one and add to local storage
    setItemCount((count) => count + 1);
}}

1.从按钮中删除onChange方法和value,它什么也不做。如果您需要显示计数,请将其显示在其他地方,而不是按钮上。
1.我不知道functionToExecute是什么。如果你想防止负值。你可以用你的州

...
const shouldDisabled = itemCount < 1
...

<Button
  id="RemoveFromCart"
  onClick={() => {
    setItemCount((count) => count - 1);
  }}
  size="large"
  variant="contained"
  endIcon={<RemoveIcon />}
  disabled={shouldDisabled}
>
  Remove From Cart
</Button>

希望这能帮到你!你可以在这里找到更多关于React状态管理的信息> https://react.dev/learn/managing-state

相关问题