rom*_*rom 7 javascript local-storage reactjs react-hooks
每当调用我的购物车组件(也如下所示)时,我都会遇到此错误(重复数千次,直到页面崩溃):
index.js:1 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.
in Cart (created by Context.Consumer)
in Route (at Routes.js:24)
in Switch (at Routes.js:23)
in Router (created by BrowserRouter)
in BrowserRouter (at Routes.js:22)
in Routes (at src/index.js:5)
Run Code Online (Sandbox Code Playgroud)
我的购物车组件:
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import Layout from "./Layout";
import { getCart } from "./cartHelpers";
import Card from "./Card";
import Checkout from "./Checkout";
const Cart = () => {
const [items, setItems] = useState([]);
useEffect(() => {
setItems(getCart());
}, [items]);
const showItems = items => {
return (
<div>
<h2>Your cart has {`${items.length}`} items</h2>
<hr />
{items.map((product, i) => (
<Card
key={i}
product={product}
showAddToCartButton={false}
cartUpdate={true}
showRemoveProductButton={true}
/>
))}
</div>
);
};
const noItemsMessage = () => (
<h2>
Your cart is empty. <br /> <Link to="/shop">Continue shopping</Link>
</h2>
);
return (
<Layout
className="container-fluid"
>
<div className="row">
<div className="col-6">
{items.length > 0 ? showItems(items) : noItemsMessage()}
</div>
<div className="col-6">
<h2 className="mb-4">Your cart summary</h2>
<hr />
<Checkout products={items} />
</div>
</div>
</Layout>
);
};
export default Cart;
Run Code Online (Sandbox Code Playgroud)
useEffect正在呼叫getCart()(如下所示):
export const getCart = () => {
if (typeof window !== "undefined") {
if (localStorage.getItem("cart")) {
return JSON.parse(localStorage.getItem("cart"));
}
}
return [];
};
Run Code Online (Sandbox Code Playgroud)
我打算getCart从 中抓取购物车localStorage并将其填充到状态变量中items或返回一个空数组[]。
根据我的理解,只要状态发生变化,useEffect 就会更改页面,并且当依赖项数组中有任何项目时,它将基于该项目。
好吧,我不明白为什么会发生这个错误。
我真的尝试过理解这个错误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,这是我迄今为止在尝试解决这个问题时学到的:
items,依赖关系,没有太大变化。测试添加 1 个项目或 0 个项目会导致数千个相同的错误我怎样才能停止这个错误?
我只是希望这个组件能够正常工作,而不会在渲染时冻结并引发数千个此错误。
Dmi*_*nko 11
原因与您的useEffect依赖关系有关:
useEffect(() => {
setItems(getCart());
}, [items]);
Run Code Online (Sandbox Code Playgroud)
问题是您在物品发生变化时传递[items]并打电话useEffect。在 useEffect 内部你正在改变items。
确保每次从
getItems()React 返回新对象或数组时,您是否不知道您的对象是相同的,并且一次又一次地调用效果。
从依赖项中删除项目
useEffect(() => {
setItems(getCart());
}, []);
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要在更改时访问当前状态:
useEffect(() => {
setItems(currentItems => getCart(currentItems));
}, []);
Run Code Online (Sandbox Code Playgroud)