【发布时间】:2021-07-02 14:53:27
【问题描述】:
我有以下useEffect():
useEffect(() => {
if (portfolios && portfolios.length > 0) {
const wLocation = portfolios.filter((portfolio: Portfolios) =>
portfolio.organizations.some(organization => organization.locations ?? false),
);
const wOutLocation = portfolios.filter((portfolio: Portfolios) =>
portfolio.organizations.every(organization => organization.locations ?? true),
);
setPortfoliosWOutLocation(getItemsWRGB(wOutLocation.map(portfolioFormatted)));
setPortfoliosWLocation(getItemsWRGB(wLocation.map(portfolioFormatted)));
}}, [portfolios]);
我的一个伙伴告诉我,我可以使用 useMemo 以避免在每次渲染中重新计算,所以我这样做了:
const portfolioWLocation = useMemo(() => {
const wLocation = portfolios.filter((portfolio: Portfolios) =>
portfolio.organizations.some(organization => organization.locations ?? false),
);
return getItemsWRGB(wLocation.map(portfolioFormatted));}, [portfolios]);
const portfolioWOutLocation = useMemo(() => {
const wOutLocation = portfolios.filter((portfolio: Portfolios) =>
portfolio.organizations.every(organization => organization.locations ?? true),
);
return getItemsWRGB(wOutLocation.map(portfolioFormatted));}, [portfolios]);
不会相同,因为 portfolios 是 useMemo() 和 useEffect() 的依赖项。
【问题讨论】:
-
嗨,何塞,欢迎来到 SO!你能澄清一下问题是什么吗?
-
嘿@YoavKadosh,我只是想知道
useMemo或在useEffect中进行计算是否有任何真正的区别,你关注我吗? -
我在这个链接stackoverflow.com/questions/56028913/…找到了解决方案
-
好的,很高兴你做到了。我也回答了你的问题,希望对你有帮助。
标签: reactjs react-hooks