渲染不同组件()时无法更新组件(应用程序)

问题描述 投票:0回答:1

我正在设计一个电子商务,当需要从购物车中删除商品时,我遇到了将返回值传递到 localStorage 函数中的删除商品的问题
具体来说这个错误:

Cart.jsx:24 Warning: Cannot update a component (
App
) while rendering a different component (
Cart
). To locate the bad setState() call inside 
Cart
, follow the stack trace as described in

我曾尝试将我的 usestate Set 方法放入带有 [] 的 useeffect 中,但不起作用
好吧,这是我的代码:

import React, { useEffect, useState } from "react";
import Navbar from "./Navbar";
import { Link } from "react-router-dom";
import Footer from "./Footer";

function Cart({ cart, setCart }) {
  const newCart = cart.flatMap((c) => c);
  const replaced = newCart.map(e => e.price.replaceAll('.', ''));
  let sum = 0

  replaced.forEach((price) => {
    sum += price * 1;
  });

  let finalSum = sum.toLocaleString()
//function to recharge page when empty all the localStorage
  function handleSubmit(e) {
    e.preventDefault();
    localStorage.clear();
    window.location.reload();
  }
//function to delete my product
  function deleteProd(id){
    const updCart = newCart.filter(e => e.id  !==id)
    setCart(updCart) //HERE IS THE ERROR
    localStorage.setItem('cart', JSON.stringify(updCart))
  }

  return (
    <>
      <Navbar />
      <h1>Carrito de Compras</h1>
      <div className="cartWrapper">
      {newCart.map((c) => (
        <div className="cartProd">
          <img src={c.img} alt="" />
          <h1>{c.prod}</h1>
          <h2>precio: ${c.price}</h2>
          <Link to={`/products/${c.id}`}>Ver producto</Link>
          <button onClick={deleteProd(c.id)}>Eliminar</button> //HERE I PASS THE PRODUCT ID TO MY FUNCTION
        </div>
      ))}
      <div className="right-bar">
        <button onClick={handleSubmit}>Vaciar Carrito</button>
        <h1>Total: ${finalSum}</h1>
      </div>
      </div>
      <Footer />
    </>
  );
}

export default Cart;


任何回复都会收到!谢谢

javascript reactjs e-commerce
1个回答
0
投票

代码中的问题在这一行:

- <button onClick={deleteProd(c.id)}>Eliminar</button>

因此,每当渲染购物车组件时,都会直接执行此函数,该函数会在渲染购物车子组件时更新父组件中的购物车状态变量,这在反应中是不允许的,因为在组件渲染时更新状态变量可能会导致意外结果。

就像你正在写东西,突然你的朋友拿起你的笔并开始更新列表,这是不好的。

这是您问题的解决方案。

有问题的代码:

  • <button onClick={deleteProd(c.id)}>Eliminar</button> // Wrong function definition

更正代码:

  • <button onClick={() => deleteProd(c.id)}>Eliminar</button> // Corrected code
© www.soinside.com 2019 - 2024. All rights reserved.