React Hook useEffect缺少一个依赖项.要么包含它,要么删除依赖数组react-hooks/精疲力竭-d



如果我添加依赖数组"在依赖数组中,就像它告诉我的那样,它会导致无限循环。另外,如果我不使用数组上的扩展操作符,那么警告不会显示,但状态变化不会呈现。

Sidebar.tsx

import { useState, useEffect } from "react";
import { Link, useLocation } from "react-router-dom";
import axios from "axios";
import getItems from "./../services/SidebarItems";
import { sidebarInfoUrl } from "./../services/ApiLinks";
function Sidebar() {
const fItems = getItems();
const location = useLocation();
const paths = location.pathname.split("/");
const [items, setItems] = useState(fItems);
useEffect(() => {
axios.get(sidebarInfoUrl).then((response) => {
const updatedItems = [...fItems]
updatedItems.forEach((item) => {
if (item.match === "projects") item.value = response.data.projects;
else if (item.match === "contacts") item.value = response.data.contacts;
});
setItems(updatedItems);
console.log("here")
});
}, []);
return (
<div className="sidebar shadow">
{items &&
items.map((item) => (
<Link
key={item.match}
to={item.link}
className={
paths[2] === item.match ? "sidebar-item active" : "sidebar-item"
}
>
<span>
<i className={item.icon}></i> {item.title}
</span>
{item.value && <div className="pill">{item.value}</div>}
</Link>
))}
</div>
);
}
export default Sidebar;

这是我从getItems()中获得的侧边栏项。

sidebarItems.ts

const items = () => {
return [
{
title: "Dashboard",
icon: "fas fa-home",
link: "/admin/dashboard",
match: "dashboard",
value: "",
},
{
title: "Main Page",
icon: "fas fa-star",
link: "/admin/main-page",
match: "main-page",
value: "",
},
{
title: "Projects",
icon: "fab fa-product-hunt",
link: "/admin/projects",
match: "projects",
value: "00",
},
{
title: "Contacts",
icon: "fas fa-envelope",
link: "/admin/contacts",
match: "contacts",
value: "00",
},
];
};
export default items;

感谢AKX。我找到我的问题了。我必须使用useMemoHook,以便我的getItem()函数在我将其添加到依赖数组时不会导致无限循环。

const fItems = useMemo(() => {
return getItems();
}, []);

不是

const fItems = getItems();

另一个修复是,
如果我不发送项目从侧边栏项目。作为一个函数,但是作为一个数组,它不会导致无限循环,即使我不使用useMemo钩子。

最新更新