【问题标题】:Fetch data from localstorage/Hooks and then delete them从 localstorage/Hooks 获取数据,然后删除它们
【发布时间】:2021-07-07 07:10:34
【问题描述】:

我有一个 React-TypeScript 项目,我正在使用动态购物车/使用 Hooks 和本地存储存储项目。交易完成后,在thankYou/页面中,我想显示我们已购买的商品,然后立即移除/清空购物车以进行新的交易。

这是我的感谢/页面:

const cart = useContext(CartContext);
....
....
{
    cart.cartItems.map(product => (
        <React.Fragment key={product.id}>
            <Col className="col-6">
                <Image src={product.photo} width="60" height="60" />
                <b>{{product.name}}</b>
            </Col>
            <Col className="col-2">{product.quantity}</Col>
            <Col className="col-2">
                {product.price}
            </Col>
         </React.Fragment>
     )
     )
}

我现在正在这样做:

<Anchor to="/" onClick={() => cart.clearCart()}>Continue Shopping</Anchor>

这是一个点击后清除购物车的链接。

我的意图:我想在加载ThankYou/页面时清除购物车内容以及Hook,但还要在执行此操作之前捕获项目并打印它。

我尝试过的-

  • 使用 useEffect() 已在页面加载时清除了购物车内容,但这会导致购物车为空。
  • localStorage -> 由于 hook 内部使用相同的概念,创建一个新的将是多余的且难以管理

我正在使用类似于this 的上下文。让我知道如何捕获商品、打印它然后删除/重置购物车以进行新交易。

【问题讨论】:

    标签: reactjs typescript react-hooks react-context


    【解决方案1】:

    您可以在登陆感谢页面时将您的购物车物品存储在状态,

    const cart = useContext(CartContext);
    const [items] = useState(cart.cartItems);
    
    useEffect(() => {
      cart.clearCart(); // clear cart once we have the items
    }, [items]);
      
    

    设置好商品后清空购物车 (useEffect())

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多