Error: Too many re-renders. struggling to save value from object in ReactHooks state

Error: Too many re-renders. struggling to save value from object in ReactHooks state

当我尝试在状态中保存值时,我遇到了项目中渲染过多的错误。基本上我正在接收对象数组,并从中计算所有项目的总价,然后按下设置 TotalPrice,但它似乎有太多重新渲染错误的问题。 我很少看到 post 说如果我们可以限制 setstate 执行的时间,可以通过附加到 onclick 事件来避免,但就我而言,我希望从中提取信息对象并进行算术运算以计算价格,然后保存在状态中。我只是没有选择来实现这一点,任何建议伙计们。谢谢

 let [totalPrice, setTotalPrice] = useState(0);
   if (basketItems) {                                
        let total = 0;
        for (let i = 0; i < basketItems.length; i++) {
               let eachItemTotalPrice = basketItems[i].price * basketItems[i].quantity;
          total = eachItemTotalPrice + total;
        }
        console.log(total);
    
        setTotalPrice(total);
  }

上面是我在状态下努力保存的代码,下面是所有代码片段

function Basket({ basketItems, updatedBasket }) {
  let [totalPrice, setTotalPrice] = useState(0);

  const increaseQuantity = (eachproduct) => {
    if (eachproduct.stockQuantity > eachproduct.quantity + 1) {
      let newProductQty = eachproduct;
      newProductQty.quantity = +eachproduct.quantity + 1;
      console.log(newProductQty);
      updatedBasket(newProductQty);
    }
  };
  const decreseQuantity = (eachproduct) => {
    if (eachproduct.stockQuantity > eachproduct.quantity + 1) {
      let newProductQty = eachproduct;
      newProductQty.quantity = +eachproduct.quantity - 1;
      console.log(newProductQty);
      updatedBasket(newProductQty);
    }
  };

  if (basketItems) {                                 // i have have error after adding this function
    let total = 0;
    for (let i = 0; i < basketItems.length; i++) {
           let eachItemTotalPrice = basketItems[i].price * basketItems[i].quantity;
      total = eachItemTotalPrice + total;
    }
    console.log(total);

    setTotalPrice(total);
  }

  
  return (
    <>
      <div className="BasketProducts">
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell> </TableCell>
                <TableCell>Product Name </TableCell>
                <TableCell> Item No./Stock Level</TableCell>
                <TableCell> Quantitiy</TableCell>
                <TableCell> Total Price</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {basketItems.map((eachproduct) => {
                let productName = eachproduct.product_name;
                let producNumber = eachproduct.producNumber;
                let price = eachproduct.price;
                let desc = eachproduct.productDescription;
                let photo = eachproduct.image_URL;
                let stockQuantity = eachproduct.stockQuantity;
                let boughtQuantitiy = eachproduct.quantity;
                return (
                  <TableRow key={producNumber}>
                    <TableCell>
                      <img className="BasketProducts-image" src={photo} />
                    </TableCell>
                    <TableCell>{productName}</TableCell>
                    <TableCell>
                      Item No:{producNumber} (InStock:{stockQuantity})
                    </TableCell>
                    <TableCell>
                      <ul style={{ float: "bottom", display: "flex", flexDirection: "column", maxWidth: "6vw" }}>
                        <li>
                          <span>{boughtQuantitiy} </span>
                        </li>
                        <li>
                          <ButtonGroup aria-label="quantityofproduct">
                            <Button variant="secondary" name="subtract" value="subtract" onClick={() => decreseQuantity(eachproduct)}>
                              -
                            </Button>
                            <Button name={productName} variant="secondary">
                              {eachproduct.quantity}
                            </Button>
                            <Button variant="secondary" name="add" value="add" onClick={() => increaseQuantity(eachproduct)}>
                              +
                            </Button>
                          </ButtonGroup>
                        </li>
                      </ul>
                    </TableCell>
                    <TableCell>£{boughtQuantitiy * price}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
      </div>
      <div>
        <TableContainer component={Paper} style={{ float: "right", display: "flex", flexDirection: "column", maxHeight: "9vw", maxWidth: "14vw" }}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Summary </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              <tr>
                <td>SubTotal:</td>
              </tr>

              <tr>
                <td>
                  <ButtonGroup aria-label="quantityofproduct"></ButtonGroup>
                  <Button variant="secondary" name="subtract" value="subtract" onclick={buyNow}>
                    Buy Now
                  </Button>
                </td>
              </tr>
            </TableBody>
          </Table>
        </TableContainer>
      </div>
    </>
  );
}

export default Basket;

BasketItems对象数组如下,

由于您添加的“功能”在父级内部,并且您正在更改该代码内的状态,因此您有一个无限循环来更改状态 -> 渲染 -> 再次更改状态等等

要修复它,您可以将代码片段放入 useEffect Hook 中,以便 运行 仅在您的组件首次呈现时出现一次

useEffect(() => {
  if (basketItems) {                                 
    let total = 0;
    for (let i = 0; i < basketItems.length; i++) {
           let eachItemTotalPrice = basketItems[i].price * basketItems[i].quantity;
      total = eachItemTotalPrice + total;
    }
    console.log(total);

    setTotalPrice(total);
  }
})