0

I am trying to render a specific Layout if the location change and I'm using the useMemo hook to validate the route and render the based on this value but it always returns true even the route change for example the new route is .../SSDSD/draft

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>
  );
}
4

1 回答 1

1

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

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]);
于 2022-01-23T10:18:54.313 回答