react大数据量渲染_UseEffect在React中运行无限渲染(超过最大更新深度)

我有一个Cart组件,里面有一系列Cards。

每次用户从购物车中删除产品时,我都会从本地存储中删除产品,

并将其从用户界面中删除。

import React, { useState, useEffect } from 'react';

import { Link } from 'react-router-dom';

import Layout from '../Layout';

import Card from '../Home/Card';

import { getCart } from './cartHelpers';

const Cart = () => {

const [items, setItems] = useState([]);

useEffect(() => {

setItems(getCart());

}, [items]);

const showItems = () => {

return (

You have {`${items.length}`} items in your cart


{items.map((prod, index) => (

....... />

))}

);

};

const noItemsMsg = () => (

Your cart is empty! Continue Shopping

);

return (

title='Shopping Cart'

desc='Manage your cart items'

className='container-fluid'

>

{items && items.length > 0 ? showItems(items) : noItemsMsg()}

Show Checkout Options / Shipping Address / Total / Update Quantity

);

};

export default Cart;

和Card.js:

import React, { useState } from 'react';

import moment from 'moment';

import { Link, Redirect } from 'react-router-dom';

import ShowImage from '../ShowImage';

import { addItemToCart, updateItem, removeItem } from '../Cart/cartHelpers';

const Card = ({product,

.............

}) => {

const [redirect, setRedirect] = useState(false);

const [countHowManyCopies, setCountHowManyCopies] = useState(product.count);

const showRemoveButton = () => {

return (

showRemoveProductBtn && (

onClick={() => removeItem(product._id)}

className='btn btn-outline-danger mt-2 mb-2'

>

Remove Product

)

)

};

return (

{product.name}

.............. // more code

{showRemoveButton()}

.............. // more code

);

};

export default Card;

每当用户点击“删除项目”按钮,我都会得到:

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

解决此问题的最佳方法是什么?

It happens because of this piece of code (items in the array):

useEffect(() => {

setItems(getCart());

}, [items]);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值