【问题标题】:Please pass either 'apiKey' or 'stripe' to StripeProvider请将 'apiKey' 或 'stripe' 传递给 StripeProvider
【发布时间】:2018-09-21 22:06:16
【问题描述】:

我以前可以正常工作,但现在我不知道发生了什么。我将 Next.js 用于 SSR,我的 Pay 元素如下所示:

class Pay extends React.Component {
  constructor() {
    super();
    this.state = { stripe: null };
  }

  componentDidMount() {
    console.log(window.Stripe)
    this.setState({
      stripe: window.Stripe('pk_test_123'),
    });
  }

  render() {
    console.log(this.state)
    return (
      <StripeProvider apiKey={this.state.stripe}>
        <Elements>
          <InjectedCheckoutForm />
        </Elements>
      </StripeProvider>
    );
  }
}

上面抛出错误:

请将“apiKey”或“stripe”传递给 StripeProvider。如果你是 使用 'stripe' 但还没有 Stripe 实例,传递 'null' 明确的。

我在这里感到困惑的是,事实上,窗口,也没有记录状态,因为页面抛出了 500 错误。 如果我删除 StripeProvider 组件,window.Stripe 会正常注销,并且 this.state 包含我的 Stripe 状态,所以我不明白它为什么会抛出错误。

【问题讨论】:

    标签: reactjs next.js stripe-payments


    【解决方案1】:

    为什么会出现错误

    &lt;StripeProvider /&gt; 想要在初始渲染上使用 apiKeystripe 属性,如错误所示。

    在您的初始渲染中,state.stripenull,因此随后是 &lt;StripeProvider apiKey=null&gt;。这会引发 500 错误,因为只有 StripeProvider 的 this.props.stripe 进行了空检查,以便它可以了解消费者方面正在发生一些异步事情。

    https://github.com/stripe/react-stripe-elements/blob/master/src/components/Provider.js#L105

    this.props.apiKeynull 会导致您出错,因为 apiKey 的处理方式不同。 https://github.com/stripe/react-stripe-elements/blob/master/src/components/Provider.js#L110

    解决方案

    我认为问题在于您只是使用了错误的属性。从StripeProvider.apiKey 切换到StripeProvider.stripe apiKey 接受string 类型,而stripe 接受StripeObject(这也是您的window.Stripe() 返回的内容)。

      <StripeProvider stripe={this.state.stripe}>
        <Elements>
          <InjectedCheckoutForm />
        </Elements>
      </StripeProvider>
    

    查看https://github.com/stripe/react-stripe-elements#loading-stripejs-asynchronouslyhttps://github.com/stripe/react-stripe-elements#server-side-rendering-ssr 的代码示例以了解更多信息。

    沙盒:https://codesandbox.io/s/x2r1pxwjqz

    尝试更改stripe -> apiKey 以查看弹出错误。

    【讨论】:

    • 啊该死的,我怎么错过了。已经解决了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2018-08-06
    • 2016-10-14
    • 2021-01-24
    • 2020-11-14
    • 2022-08-23
    • 2022-01-05
    相关资源
    最近更新 更多