简体   繁体   中英

shopping cart array not rendering properly, react.js

after a fetch if I click to some card I am able to populate an empty array. I would like to pass it as a prop to a child component and I guess I am doing the right way, the problem occurs when within the children I am trying to console log it because I can not see any errors and the console.log is not printing anything


let shoppingCart = [];

const fetchProducts = async () => {
const data = await fetch(
  "blablablablablab"
);
const products = await data.json();
setProducts(products);
console.log(products);
};


const handleShoppingCart = product => {
  shoppingCart.push(product);
  console.log(shoppingCart);
  return shoppingCart;
};

Inside the return function I tried to check if the array was not empty, if was not undefined or if was not null but with the same result

{shoppingCart.length !== 0 ? (
    <ShoppingCart parkingSlots={shoppingCart} />
  ) : null}

children component

const ShoppingCart = ({ parkingSlots }) => {
  console.log(parkingSlots);
  const parkingSlotsComponent = parkingSlots.map((parkingSlot, i) => {
  // const { name } = parkingSlot;
  return (
    <div className="parking_details" key={i}>
      {parkingSlot.name}
    </div>
  );
});
return <div className="checkout">{parkingSlotsComponent}</div>;
 }; 

The data is in props .

When data is passed to child component via props , then it is part of props child component. Try below and see if you can console log the data.

const ShoppingCart = props => {
  console.log(props.parkingSlots);
  const parkingSlotsComponent = props.parkingSlots.map((parkingSlot, i) => {
  // const { name } = parkingSlot;
  return (
    <div className="parking_details" key={i}>
      {props.parkingSlot.name}
    </div>
  );
});
return <div className="checkout">{parkingSlotsComponent}</div>;
 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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