状态未在 axios 调用后更新 Next js

发布于 2025-01-16 00:02:41 字数 3047 浏览 0 评论 0原文

我正在开发一个电子商务服务 Nextjs 和 Paypal 支付服务。 这是我的产品组件

const Product = () => {
  const router = useRouter();
  const { id, category } = router.query;
  const [product, setProduct] = useState();
  const [amount, setAmount] = useState(1);

  useEffect(() => {
    if (category) {
      const foundProduct = products[category].find(
        (element) => element.id == id
      );
      setProduct({ ...foundProduct, amount, total: foundProduct.price * amount });
    }
  }, [id, amount]);

  
  return (
    <>
      {!product ? (
        <Spinner />
      ) : (
        <div className="product-wrapper">
          <div className="product-image">
            <Image src={product.image} />
          </div>
          <div className="product-info">
            <h3>{product.title}</h3>
            <p className="product-price">
              {product.currency} {product.price}
            </p>
            <p className="product-description">
              {product.description}
            </p>
            <div className="product-cart-container">
              <div className="product-cart-handle">
                <p onClick={() => amount > 1 && setAmount(amount - 1)}>-</p>
                <span>{amount}</span>
                <p onClick={() => setAmount(amount + 1)}>+</p>
              </div>
              <BuyButtton item={product} amount={amount} />
            </div>
            <div className="product-general">
              <p>General information</p>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

,这是我的 BuyButton 组件

const BuyButtton = ({ item }) => {
  useEffect(() => {
    console.log(item);
  }, [item]);
  return (
    <div>
      <PayPalScriptProvider
        options={{
          "client-id":"",
        }}
      >
        <PayPalButtons
          createOrder={async () => {
            try {
              const res = await axios({
                url: "http://localhost:3000/api/payment",
                method: "POST",
                headers: {
                  Accept: "application/json",
                  "Content-Type": "application/json",
                },
                data: JSON.stringify(item),
              });
              return res.data.id;
            } catch (error) {
              console.log(error);
            }
          }}
          onApprove={(data, actions) => {
            console.log(data);
            actions.order.capture();
          }}
          style={{ layout: "horizontal", color: "blue" }}
        />
      </PayPalScriptProvider>
    </div>
  );
};


所以当我将此道具项目传递给我的 BuyButton 组件时工作正常,金额和总价值更新正确,问题是当我执行 axios 调用时,看起来组件存储了item 属性的初始值,因此 amount 和 value 永远不会改变,它总是 amount:1,value:item.value。有什么想法吗?谢谢,

我尝试将 item 道具存储在一个状态中,但它没有按我的预期工作

i'm developing an ecommerce whit Nextjs and payments with Paypal.
This is my product component

const Product = () => {
  const router = useRouter();
  const { id, category } = router.query;
  const [product, setProduct] = useState();
  const [amount, setAmount] = useState(1);

  useEffect(() => {
    if (category) {
      const foundProduct = products[category].find(
        (element) => element.id == id
      );
      setProduct({ ...foundProduct, amount, total: foundProduct.price * amount });
    }
  }, [id, amount]);

  
  return (
    <>
      {!product ? (
        <Spinner />
      ) : (
        <div className="product-wrapper">
          <div className="product-image">
            <Image src={product.image} />
          </div>
          <div className="product-info">
            <h3>{product.title}</h3>
            <p className="product-price">
              {product.currency} {product.price}
            </p>
            <p className="product-description">
              {product.description}
            </p>
            <div className="product-cart-container">
              <div className="product-cart-handle">
                <p onClick={() => amount > 1 && setAmount(amount - 1)}>-</p>
                <span>{amount}</span>
                <p onClick={() => setAmount(amount + 1)}>+</p>
              </div>
              <BuyButtton item={product} amount={amount} />
            </div>
            <div className="product-general">
              <p>General information</p>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

and this is my BuyButton component

const BuyButtton = ({ item }) => {
  useEffect(() => {
    console.log(item);
  }, [item]);
  return (
    <div>
      <PayPalScriptProvider
        options={{
          "client-id":"",
        }}
      >
        <PayPalButtons
          createOrder={async () => {
            try {
              const res = await axios({
                url: "http://localhost:3000/api/payment",
                method: "POST",
                headers: {
                  Accept: "application/json",
                  "Content-Type": "application/json",
                },
                data: JSON.stringify(item),
              });
              return res.data.id;
            } catch (error) {
              console.log(error);
            }
          }}
          onApprove={(data, actions) => {
            console.log(data);
            actions.order.capture();
          }}
          style={{ layout: "horizontal", color: "blue" }}
        />
      </PayPalScriptProvider>
    </div>
  );
};


So when i pass this props item to my BuyButton component works fine, the amount and total value updates correctly, the problem is when i do the axios call, it looks like the component stores the initial value of the item prop, so amount and value never changes, its always amount:1, value:item.value. Any ideas? Thanks

I tried storing the item prop in a state but it didin't work as i expected

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮云落日 2025-01-23 00:02:42

Product 组件中,您传递 item & amountBuyButton

您还需要将 amount 添加到 BuyButton 组件。

const BuyButtton = ({ 商品, 金额 }) =>; {

并在 axios 调用中传递请求正文中的金额

data: JSON.stringify(item),
// need to add the amount data 

In the Product component, you are passing item & amount to BuyButton

<BuyButtton item={product} amount={amount} />.

You need to add the amount to the BuyButton component as well.

const BuyButtton = ({ item, amount }) => {

and pass the amount in the request body in the axios call

data: JSON.stringify(item),
// need to add the amount data 
巾帼英雄 2025-01-23 00:02:41

解决我的问题的解决方案是将forceReRender prop添加到PayPalButtons,例如forceReRender = {[item]},因此它重新渲染按钮并获取新的金额值

The solution that solved my problem was adding forceReRender prop to PayPalButtons like this forceReRender={[item]}, so it re-render the button and gets the new amount value

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文