You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS头部迷你购物车计数器:子组件更新状态同步父组件

带商品计数器的迷你购物车移除功能问题及解决方法

我正在NextJS中开发一个基础的带商品计数器的头部迷你购物车,当前在头部组件中使用表单状态值,并在头部的子组件中渲染该数值。提交表单时商品总数能正常显示,头部计数器和迷你购物车中的数值符合预期,但点击迷你购物车中的移除商品按钮时,希望将计数器状态从当前值重置为0,并重新渲染头部、迷你购物车及购物车商品组件,使迷你购物车中的商品再次隐藏。

当前组件结构

product-form.js

import React, { useState, useRef, useEffect } from "react";

export default function ProductForm(props) {
  const [count, setCount] = useState(0);

  const numberInput = useRef(null);

  useEffect(() => {
    numberInput.current.dispatchEvent(
      new Event("change", {
          detail: {
              newValue: count,
          },
          bubbles: true,
          cancelable: true,
      })
    );
  }, [count]);

  return (
    <>
     <div>
        <button onClick={() => {setCount(count - 1)}}>
         Decrease
        </button>
       <Input 
        value={count}
        ref={numberInput}
        onChange={(e) => setCount(e.target.value)}>
        <button onClick={() => {setCount(count + 1)}}>
         Increase
        </button>
     </div>
     <button onClick={event => props.onClick(() => event.currentTarget.parentNode.parentNode.querySelector('#product-qty-input').value)}>Add to Cart</button>
    </>
  )
}

header.js

import React, { useState } from "react";
import MiniCart from './minicart'

export default function HeaderRight({count}) {
  const [cartItemCount, setCartItemCount] = useState([]);
  return (
    <>
     <span>You have {count} items </span>
     <MiniCart count={count} />
    </>
  )
}

mini-cart.js

import CartItem from "./cartitem";
import CartEmpty from "./cartEmpty";

export default function MiniCart({count}) {
  return (
    <>
     { count == 0 && 
       <CartEmpty />
     }
     { count > 0 &&
        <CartItem count={count} />
     }
    </>
  )
}

mini-cart-item.js

export default function CartItem({count}) {
  return (
    <>
      <p>Product Name</p>
      <p>Unit Price: $125.00</p>
      <p>x{count}</p>
      <p>$375.00</p>
      <button>REMOVE ITEM</button>
    </>
  )
}

解决方法(更新于2022/09/07)

通过将状态更新函数setCartCountState传递给所有嵌套子组件,在mini-cart-item.js组件中创建点击事件,使用以下函数将计数器重置为0,从而隐藏迷你购物车商品:

// 点击移除按钮时将countState重置为0,移除商品
const changeState = () => {
  countState("0");
}

内容的提问来源于stack exchange,提问作者Hellodan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:30:28