首页 > 解决方案 > React, availableForSale: true 为 true 时显示 Text

问题描述

我使用 Shopify 作为我的后端并作为我的前端做出反应,当 product.availableforsale 为真时,我希望它在库存中打印出来。这是我的产品页面上的代码。我已经评论了 {product.availableForSale} 在产品页面组件中的代码。

import React, { useEffect, useContext, useState } from "react";
import { useParams } from "react-router-dom";
import { ShopContext } from "../../context/shopContext";
import { Text, Div, Button, Row, Col, Container, Image } from "atomize";
import { Link } from "react-router-dom";
import "./ProductPage.css";
import { Spinner } from 'react-bootstrap';
//Res
// const theme = {
//   grid: {
//     colCount: 8,
//     gutterWidth: 0
//   }
// };

const ProductPage = () => {
  let { id } = useParams();
  const { fetchProductWithId, addItemToCheckout, product, client } = useContext(
    ShopContext
  );

  //Fav
  const [favoriteText, setFavoriteText] = useState("Add to Favorite");

  //Variants
  const [sizeIndex, setSizeIndex] = useState('');
  const [posterIndex, setPosterIndex] = useState('');
  

  useEffect(() => {
    fetchProductWithId(id);
    return () => {};
  }, [fetchProductWithId, id]);

  if (!product.title) return <div className="prod-spinner-container"><Spinner animation="border" variant="primary" /></div>

//Variants
  const selectedVariant = client.product.helpers.variantForOptions(product, {
    Size: sizeIndex || product.options[0].values[0].value,  
     Poster: posterIndex || product.options[1].values[0].value
  });

  return (

    <Container>
      
      <div className={"row"} >
      
      <Div className="prod-img" p="1.5rem">
          <Image src={product.images[0].src} w="20rem" p="2rem"/>
      </Div>
      <div className="prod-size col-12 col-sm-6  " pos="Center" key={product.id}>
          <Text className="title-txt"tag="h1" textColor="white" textWeight="500" m={{ y: "2rem" }} >
            {product.title}
          </Text>

          <Text className="title-txt"tag="h1" textColor="white" textWeight="500" m={{ y: "2rem" }} >
            {/* Print Out text? */}
            {product.availableForSale}
            {product.vendor}
          </Text>

          {/* Selected variant will allow the price to change due to frame size etc */}
          
          <Text className="cost-txt" tag="h3" textColor="white" m={{ y: "2rem" }} textWeight="100">
         Price € {selectedVariant?.price} Excl Shipping
          </Text>

          {/* Poster size */}
          <Text>Size (inc)</Text>
          <select className="custom-select" value={posterIndex} onChange={e => setPosterIndex(e.target.value)} >
            {product.options[1].values.map((item, index) => (
              <option value={item.value}>{item.value}</option>
            ))
            }
          </select>         

          <Text>Frame</Text>
          <select className="custom-select" value={sizeIndex} onChange={e => setSizeIndex(e.target.value)} >
            {product.options[0].values.map((item, index) => (
              <option value={item.value}>{item.value}</option>
            ))
            }
          </select>


          <Button
            rounded="lg"
            shadow="3"
            bg="black500"
            m={{ y: "2rem" }}
            onClick={() => addItemToCheckout(selectedVariant?.id, 1)}
          >
            Add to Cart
          </Button>
          <Button  rounded="lg"
            shadow="3"
            bg="black500"
            m={{ y: "2rem" }}
            onClick={() => {
            // console.log(product);
            let favorites = JSON.parse(localStorage.getItem('favorites') || "[]");
            const productExists = favorites.find(favorite => favorite.id === product.id);
            if(productExists) {              
              favorites = favorites.filter(favorite => favorite.id !== product.id);
              setFavoriteText("Add to Favorite")
              localStorage.setItem('favorites', JSON.stringify(favorites));
              
            } else {
              favorites = [...favorites, product];
              setFavoriteText("Remove from Favorite");
              localStorage.setItem('favorites', JSON.stringify(favorites));
            }

          }}>
             {/* <HeartIcon title="Add to Favourites" style={{height: '25px', width: '25px', backgroundColor: "#fff", color: "red" }} /> */}
            {favoriteText}
          </Button>
        </div>
      </div>
    </Container>
  );
};

export default ProductPage;

任何帮助将不胜感激,谢谢。如果需要更多代码,请告诉我谢谢

标签: reactjssdkapkshopify

解决方案


如果您只希望一个条件显示缺货,请使用此

    {product.availableForSale && 
     <Text className="title-txt"tag="h1" textColor="white" textWeight="500" m={{ y: "2rem" }} >
         {/* Print Out text? */}
         {product.vendor}
     </Text>
    }

或者

{product.availableForSale ?
  <Text className="title-txt"tag="h1" textColor="white" textWeight="500" m={{ y: "2rem" }} >
    {/* Print Out text? */}
    {product.vendor}
  </Text>
 :<div>Available</div>
}

推荐阅读