无法访问JavaScript对象中的属性

kg7wmglp  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(314)

我是JavaScript新手,我正在做一个项目,我需要访问JavaScript对象中的prices属性。此对象是来自条带集成的产品对象。当我记录productData.prices时,它显示undefined,即使productData对象具有prices属性。我不知道为什么会这样。有人可以帮助我了解可能导致此问题的原因吗?
下面是JavaScript代码

export default function Subscription() {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState([]);
  const { currentUser } = useAuth();
  const [stripe, setStripe] = useState(null);

  useEffect(() => {
    const initializeStripe = async () => {
      const stripe = await loadStripe(
        process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY
      );
      setStripe(stripe);
    };

    initializeStripe();

    const q = query(collection(db, "products"), where("active", "==", true));
    getDocs(q).then((querySnapshot) => {
      const products = {};
      querySnapshot.forEach(async (doc) => {
        products[doc.id] = doc.data();
        const priceSnapshot = await getDocs(
          collection(db, "products", doc.id, "prices")
        );
        priceSnapshot.forEach((price) => {
          products[doc.id].prices = {
            priceId: price.id,
            priceData: price.data(),
          };
        });
      });
      setProducts(products);
    });
  }, []);

  async function loadCheckOut(priceId) {
    setLoading(true);
    const usersRef = doc(collection(db, "users"), currentUser.uid);
    const checkoutSessionRef = collection(usersRef, "checkout_sessions");

    const docRef = await addDoc(checkoutSessionRef, {
      price: priceId,
      trial_from_plan: false,
      success_url: window.location.origin,
      cancel_url: window.location.origin,
    });

    onSnapshot(docRef, (snap) => {
      const { error, sessionId } = snap.data();
      if (error) {
        alert(`An error occurred: ${error.message}`);
      }

      if (sessionId && stripe) {
        stripe.redirectToCheckout({ sessionId });
      }
    });
  }

  return (
    <>
      <Container className="mt-4 mb-4">
        <h1 className="text-center mt-4">Choose Your Plan</h1>
        <Row className="justify-content-center mt-4">
          {Object.entries(products).map(([productId, productData]) => {
            console.log(productData);
            console.log(productData.prices);

            return (
              <Col md={4} key={productId}>
                <Card>
                  <Card.Header className="text-center">
                    <h5>{productData.name}</h5>
                    <h5>$20.00 / month</h5>
                  </Card.Header>
                  <Card.Body>
                    <h6>{productData.description}</h6>
                    <Button
                      onClick={() => loadCheckOut(productData?.prices?.priceId)}
                      variant="primary"
                      block
                      disabled={loading}
                    >
                      {loading ? (
                        <>
                          <Spinner
                            animation="border"
                            size="sm"
                            className="mr-2"
                          />
                          Loading...
                        </>
                      ) : (
                        "Subscribe"
                      )}
                    </Button>
                  </Card.Body>
                </Card>
              </Col>
            );
          })}
        </Row>
      </Container>
    </>
  );
}

console.log(productData);记录以下对象

{
    "images": [],
    "description": "Access to dashboard",
    "tax_code": null,
    "active": true,
    "role": "premium",
    "name": "Premium",
    "metadata": {
        "firebaseRole": "premium"
    },
    "prices": {
        "priceId": "price_1N7SdbJHqW6OBlJ5itJgsGON",
        "priceData": {
            "billing_scheme": "per_unit",
            "interval": "month",
            "unit_amount": 2000,
            "currency": "usd",
            "product": "prod_NtF7pDBsqj5psh",
            "transform_quantity": null,
            "type": "recurring",
            "active": true,
            "metadata": {},
            "tax_behavior": "unspecified",
            "tiers": null,
            "tiers_mode": null,
            "interval_count": 1,
            "recurring": {
                "interval": "month",
                "aggregate_usage": null,
                "usage_type": "licensed",
                "interval_count": 1,
                "trial_period_days": null
            },
            "description": null,
            "trial_period_days": null
        }
    }
}

console.log(productData.prices);日志未定义。有人能帮助我了解这里发生了什么,以及我如何解决它?谢谢你。

gjmwrych

gjmwrych1#

根据你提供的代码💁🏻‍♂️我认为,products对象在控制台中显示的方式如下👀:

{"key":"value"}

👨🏻‍🏫 在这里,键以实际字符串的形式呈现,🤸🏻‍♂️在另一种方式中,products obj在控制台中的格式类似于JSON数据,因此当您想要访问它时,如products.property,它将无法工作,除非您使用以下命令从{"key":"value"}解析为{key:"value"}

JSON.parse(products);

它将把它转换成一个具有可访问属性实际javascript对象👌🏻。或者你可以使用💁🏻‍♂️:

products["property"]

希望能成功👀

相关问题