【问题标题】:useMemo hook always True even the location.pathname changeuseMemo 钩子总是 True 即使 location.pathname 改变
【发布时间】:2022-01-23 18:30:09
【问题描述】:

如果位置发生变化,我会尝试呈现特定的布局,并且我正在使用 useMemo 挂钩来验证路线并基于此值呈现,但即使路线发生变化,它也始终返回 true,例如新路线是 . ../SSDSD/草稿

const location = useLocation();
  console.log(location)
  const showShadow = useMemo(() => ['preview', 'signing', 'receipts'].some(word => location.pathname.includes(word)), [location]);
  const isHomePage = useMemo(() => ['/', '/search', '/addressbook'].some(word => location.pathname.includes(word)), [location]);
  console.log(isHomePage);
  //debugger;
  return (
    <ThemeProvider theme={theme}>
      <Box className={isHomePage ? classes.homeBackground : classes.innerBackground}>
      </Box>
    </ThemeProvider>
  );
}

【问题讨论】:

  • 尝试使用location.pathname作为依赖
  • 还是一样的``` const isHomePage = useMemo(() => ['/', '/search', '/addressbook'].some(word => location.pathname.includes(字)),[位置.路径名]); ``` 控制台 ``` console.log(location) ``` 对象哈希:"" key: "vvj7z7" 路径名:"/EP1001E2K/draft" 搜索:"" state: null [[Prototype]]: Object ` ``console.log(isHomePage); ``` Layout.js:66 真
  • 在 useMemo 的回调中记录路径名并检查它是否正在更新

标签: javascript reactjs react-router-dom react-usememo


【解决方案1】:

问题是您在数组中包含"/"location.pathname 总是以 "/" 开头,所以这总是正确的。

const result = ['/', 'any string', 'any other string', 'doesnt matter'].some(str => location.pathname.includes(str));
console.log(result); // always true

相反,您可能希望包含所有实际代表您的“主页”的路径名,并使用str.startsWith 而不是str.includes,使用如下内容:

const isHomePage = useMemo(() => (
  location.pathname === '/'
  || ['/search', '/addressbook'].some(str => location.pathname.startsWith(str))
), [location]);

【讨论】:

    猜你喜欢
    • 2019-08-20
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2021-11-08
    • 2011-11-02
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多