请将“apiKey”或“stripe”传递给 StripeProvider

K20*_*0GH 5 stripe-payments reactjs next.js react-stripe-elements

我以前在这方面工作得很好,但我现在对发生的事情感到困惑。我将 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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

以上抛出错误:

请将“apiKey”或“stripe”传递给 StripeProvider。如果您正在使用 'stripe' 但还没有 Stripe 实例,请显式传递 'null'。

不过,我在这里感到困惑的是,由于页面抛出 500 错误,因此窗口和状态都不会被记录。如果我删除 StripeProvider 组件,window.Stripe 会正常注销,而 this.state 包含我的 Stripe 状态,所以我不明白为什么会抛出错误。

Cha*_*hau 7

为什么你会收到错误

<StripeProvider />想要初始渲染上的apiKeyorstripe道具,如错误所示。

在您的初始渲染中,state.stripenull,然后是<StripeProvider apiKey=null>。这会引发 500 错误,因为只有 StripeProviderthis.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.apiKeyStripeProvider.stripe apiKey接受一个string类型而stripe接受一个StripeObject(这也是你的window.Stripe()回报)。

  <StripeProvider stripe={this.state.stripe}>
    <Elements>
      <InjectedCheckoutForm />
    </Elements>
  </StripeProvider>
Run Code Online (Sandbox Code Playgroud)

观察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以查看弹出的错误。