这是我的代码
const Head: FC<{ match: faceMatch<{}> }> = ({ match }) => {
const [arrProd, setArrProd] = useState<JSX.Element[]>([]);
const [ImgCatIndx, setImgCatIndx] = useState<number>(0);
const [resError, setResError] = useState<string>("");
useMemo(() => {
setImgCatIndx(0);
}, [match]);//warning React Hook useMemo has an unnecessary dependency
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
document.title = `Hat Jacket Pants Shoes Suit | Amasia`;
(async () => {
setArrProd([]);
setResError("");
try {
const Res = await fetch(
`https://foo0022.firebaseio.com/New/${headcateg[ImgCatIndx]}.json`,
{
signal: signal
}
);
if (!Res.ok) {
throw new Error("Page Not Found 404");
}
const ResObj = await Res.json();
const ResArr = await Object.values(ResObj).flat();
await setArrProd(
ResArr.map(
({
to,
id,
price,
src,
title,
sold,
shipping
}: faceProductList) => (
<Fragment key={id}>
<NavLink to={to}>
<img
src={`/${src[0]}`}
alt={title}
height={"220px"}
width={"220px"}
/>
<span>{price}</span>
<span>{shipping}</span>
<span>{sold}</span>
</NavLink>
</Fragment>
)
)
);
} catch (error) {
if (error.name !== "AbortError") {
setResError(error.message);
}
}
})();
return () => {
abortController.abort();
};
}, [ImgCatIndx]);
if (resError !== "") {
return <HandlerErr error={resError} />;
} else if (!arrProd.length) {
return <Loding />;
}
return(....)
我进入控制台。
React Hook useMemo具有不必要的依赖项:“ match”。排除它>或删除依赖项数组。
我想在更改匹配项时发生更改,并且ImgCatIndx =0。目前尚不清楚为什么在这里收到警告。如何与之相关。如何解决警告?
答案 0 :(得分:2)
您应该使用useEffect而不是useMemo。如果使用react路由器,则即使更新了相同的参数并正确地自行传递了参数,匹配对象也会在历史记录更新时发生变化。