【问题标题】:Stripe + NextJs - window is not definedStripe + NextJs - 未定义窗口
【发布时间】:2020-06-25 23:35:29
【问题描述】:

我正在尝试在 NextJs 中使用 Stripe https://github.com/stripe/react-stripe-elements/blob/master/README.md#server-side-rendering-ssr

我不断收到错误消息“未定义窗口”。我错过了什么吗?代码在上面的链接中。

【问题讨论】:

标签: reactjs stripe-payments next.js


【解决方案1】:

"window is not defined" 之所以显示,是因为您的代码是 server-side 呈现的,并且无法访问全局 window 对象,因为这只是一个客户端会明白。将您的代码移动到 lifecycle methods 中,因为它们仅在 client-side 上运行。

【讨论】:

  • 生命周期方法有哪些?
【解决方案2】:

另一种选择是对 Stripe 组件使用动态导入并禁用 SSR。

StripeForm 组件文件(默认导出)
component/StripeForm.tsx

像这样在pages/stripe中动态导入

const StripeForm = dynamic(() => import("../components/StripeForm"), { ssr: false } )

return (
   ...
   <StripeForm />
   ...
)

【讨论】:

    猜你喜欢
    • 2019-10-12
    • 2021-03-30
    • 2019-10-05
    • 2020-09-18
    • 1970-01-01
    • 2022-12-24
    • 2019-11-07
    • 2022-06-19
    • 1970-01-01
    相关资源
    最近更新 更多