gpt4 book ai didi

javascript - 如何设置所需浏览器 'window' 变量的状态

转载 作者:行者123 更新时间:2023-12-02 23:19:13 27 4
gpt4 key购买 nike

我决定重新表述我的问题。

我有一个名为“sku”的组件,它使用 stripe 设置其公钥,然后在渲染中我使用该 stripe 访问状态与 graphql 配对来提取数据。

我遇到的问题是在 netlify 上运行它或构建它时,无法访问构建窗口变量。

解决方法是将语句包装在 if (typeof window !== 'undefined') 条件中,以使构建成功。但问题是你不能用 if 语句包装组件状态。

我不知道如何解决这个问题...

有问题的组件:

import React, { Component } from 'react'
import { graphql, StaticQuery } from 'gatsby'
import SkuCard from './skuCard'

const conatinerStyles = {
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-evenly',
padding: '1rem 0 1rem 0',
}

class Skus extends Component {
// Initialise Stripe.js with your publishable key.
// You can find your key in the Dashboard:
// https://dashboard.stripe.com/account/apikeys
// state = { stripe : 'test' }
// componentDidMount() {
// if (typeof window !== 'undefined') {
state = {
stripe: window.Stripe('pk_test_IhM5g81HgmeLxC0CHNoisiRg00084h8HyH', {
betas: ['checkout_beta_4'],
}),
// }
// }
}

render() {
return (
<StaticQuery
query={graphql`
query SkusForProduct {
skus: allStripeSku {
edges {
node {
id
currency
price
attributes {
name
}
}
}
}
}
`}
render={({ skus }) => (
<div style={conatinerStyles}>
{skus.edges.map(({ node: sku }) => (
<SkuCard key={sku.id} sku={sku} stripe={this.state.stripe} />
))}
</div>
)}
/>
)
}
}

export default Skus

最佳答案

像这样的事情怎么样?

const stripe = () => {
let stripe = undefined;
if (typeof window !== "undefined") {
stripe = window.Stripe("pk_test_IhM5g81HgmeLxC0CHNoisiRg00084h8HyH", {
betas: ["checkout_beta_4"]
});
}
return stripe;
};

class Skus extends Component {
state = {
stripe: stripe()
};
//
// Rest of your component
//
}

让我知道它是否有效。

关于javascript - 如何设置所需浏览器 'window' 变量的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57023227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com