javascript 状态更改时更新条带PaymentRequest 'on'事件

yyhrrdl8  于 2024-01-05  发布在  Java
关注(0)|答案(1)|浏览(131)

我使用stripe PaymentRequestButton添加苹果支付和谷歌支付现在,我们需要stripe PaymentRequest对象。然后我们监听一些事件使用
PaymentRequest.on('paymentmethod, async (e)=>{ // Here are my states etc })
现在,这是在一个useEffect中,useEffect依赖于state,如amount。但更改amount不会影响此事件,我想更新eventListeners
这是我的代码

let pr = null;

const StripeCheckoutForm = ({ amount, subscription, websiteName }) => {
  const stripe = useStripe();

  const [paymentRequest, setPaymentRequest] = useState(null);
  const [errorMessage, setErrorMessage] = useState("");

  useEffect(() => {
    if (stripe) {
      pr = stripe.paymentRequest({
        country: "CA",
        currency: "cad",
        requestPayerName: true,
        requestPayerEmail: true,
        total: { label: websiteName, amount: 1000 },
      });

      pr.canMakePayment().then((result) => {
        if (result) {
          setPaymentRequest(pr);
        }
      });

      // Code inside this block doesn't change on state change. 
      // It runs on the state values with which it was mounted.
      // I tried unmounting, cleaning functions, etc but that doesn't work

      pr.on("paymentmethod", async (e) => {
       
          const functions = firebase.functions();
          console.log(subscription);
          if (subscription) {
            console.log("Subscription");
           
            e.complete("success");
          } else {
            console.log("One time");
            
          }
      
      });

      pr.on("cancel", async (e) => {
        setErrorMessage("Payment box cancelled");
      });
    }
  }, [stripe, subscription, amount, websiteName]);

  return (
    <div className="stripe-checkout-form-component">
      <div className="payment-request-buttons-container">
        {paymentRequest && (
          <PaymentRequestButtonElement options={{ paymentRequest }} />
        )}
        <div className="payment-request-error">{errorMessage}</div>
      </div>
    </div>
  );
};

字符串

5vf7fwbs

5vf7fwbs1#

GitHub上的答案解决了这个问题!
在这里引用它,以防万一:
据我所知,这不在官方文档中,但我能够找到一种方法来删除任何不需要的额外侦听器。
方法一:你可以调用paymentRequest.removeAllListeners()来删除所有现有的监听器,然后重新附加一个你选择的监听器。我相信这会删除paymentRequest中的所有回调,如果你有其他监听器,比如on click,或者你想保留的token,这可能不是你想要的行为。
方法二:您还可以检查paymentRequest对象是否已经附加了某种类型的侦听器,在这种情况下只需删除该特定侦听器。

if (paymentRequest.hasRegisteredListener('paymentmethod')) {  
  paymentRequest.off('paymentmethod'); 
}
 
paymentRequest.on('paymentmethod', ...);

字符串

相关问题