PayPalButtons 回调函数获取过时数据

PayPalButtons callback function gets stale data

提问人:Ruben Lemiengre 提问时间:8/18/2023 最后编辑:Ruben Lemiengre 更新时间:8/18/2023 访问量:32

问:

我有以下代码,这是一个带有PayPal按钮的订单组件:

const Order = () => {
   const { order } = useOrderData();
   console.log("order (1):", order)

   const onPaypalCreateOrder = async (data, actions) => {
      console.log("order (2):", order)
      // ... 
   }

   return (
      <>
         <PayPalScriptProvider>
            <PayPalButtons
               createOrder={onPaypalCreateOrder}
            />
         </PayPalScriptProvider>
         <div>
         // (there's code here which allows me to update the order object asynchronously)
         </div>
      </>
   )
}

我去掉了不相关的代码来简化事情。

订单组件加载后,我看到:
order (1):(订单对象的原始值)

当我做一些改变订单对象的事情时,我会看到:
order (1):(订单对象的新值)
因此,useOrderData 正确地向 Order 组件提供了新的订单对象。

当我现在单击PayPal按钮时,我看到:
订单 (1):(订单对象的新值) 订单 (2):(订单对象的原始值)

因此,即使在进行更改之后,我的订单组件也会从 useOrderData 钩子中获取订单对象的最新值。 但出于某种原因,PayPalButtons 组件始终使用过时的数据。

在PayPalButtons组件中定义订单时,我试图通过将订单对象传递给onPaypalCreateOrder函数来修复它:

const onPaypalCreateOrder = async (data, actions, order) => {
   console.log("order (2):", order)
   // ... 
}

<PayPalButtons
   createOrder={async (data, actions) => {
      console.log("order (3):", order)
      await onPaypalCreateOrder(data, actions, order)
   }}
/>

这没有任何区别。即使在这里,我也得到了:
订单 (1):(订单对象的新值) 订单 (2):(订单对象的原始值) 订单 (3):(订单对象的原始值)

我还尝试将 onPaypalCreateOrder 包装在 useCallback 中:

const onPaypalCreateOrder = useCallback(async (data, actions) => {
      console.log("order (2):", order)
      // ... 
   }, [order])

这也没有任何区别。

如何在 onPaypalCreateOrder 函数中获取订单对象的最新值?

javascript reactjs 关闭 PayPal 按钮

评论


答: 暂无答案