【问题标题】:How to pull out JSON values from Stripe output如何从 Stripe 输出中提取 JSON 值
【发布时间】:2021-08-23 00:22:51
【问题描述】:

我试图在我的 Stripe JSON 输出的标签中简单地显示“amount_total”,但我不断收到以下错误:

TypeError:无法读取未定义的属性“地图”

这是 Stripe 输出的一部分:

{
  "session": {
    "id": "cs_test_w3GvxNyitVrBsC6nB8SlaLx6gYxeGD1mVwrTVb0YIx8feZPt1FoBe76IY5",
    "object": "checkout.session",
    "allow_promotion_codes": null,
    "amount_total": 6700,
    "billing_address_collection": null,
    "cancel_url": "http://localhost:3000/checkout",
    "client_reference_id": null,
    "currency": "usd",
  }
}

这是我正在使用的 React (Next.js) 代码:

export default function learn() {

  const handleClick = async (event) => {
    const { sessionId } = await fetch('/api/checkout/session', {
      method: 'POST',
      headers: {
        "content-type": "application/json"
      },
      body: JSON.stringify({ quantity: 1 })
    }).then(res => res.json())
    const stripe = await stripePromise;
    const { error } = await stripe.redirectToCheckout({
      sessionId,
    })
  }

  const router = useRouter();

  const { data, error } = useSWR(
    router.query.session_id 
      ? `/api/checkout/${router.query.session_id}` 
      : null,
    (url) => fetch(url).then(res => res.json())
  )

  return (
    <>
    <Nav />
      <div>
        <h1>Payment Result:</h1>
        <pre>{data ? JSON.stringify(data, null, 2) : 'Loading...'}</pre>
        
        {data.map((amount) => (
          <h1>{amount.amount_total}</h1>
        ))}
      
        <button role="link" onClick={handleClick}>
          Checkout
        </button>
      </div>
    </>
  )
}

【问题讨论】:

    标签: reactjs next.js stripe-payments


    【解决方案1】:

    我猜你的“数据”变量是空的。这就是“map”方法/函数有错误的原因。您不会将“数据”变量分配给从 url 获得的数据。

    【讨论】:

      【解决方案2】:

      查询是异步的,所以当你的 jsx 被渲染时,数据是空的。获取数据时,您需要在副作用中执行此操作,因此您希望在“useEffect”挂钩中运行它 - 然后在它返回时更新数据对象。

      看看这篇文章的一些例子: https://maxrozen.com/fetching-data-react-with-useeffect

      【讨论】:

        猜你喜欢
        • 2021-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-12
        • 2018-11-21
        • 1970-01-01
        • 1970-01-01
        • 2017-10-14
        相关资源
        最近更新 更多