条件渲染导航

时间:2021-07-13 22:07:41

标签: reactjs graphql gatsby datocms

嗨,我需要条件渲染我的导航。我使用 Gatsby 和 GraphQl。我有导航组件,取决于我需要呈现不同导航的路线。问题是我不能做有条件的 useStateStatic 钩子。我在我的源代码中做了两个不同的导航,它是 DatoCMS,但我无法查询它。

const Navigation = () => {
  const pathName = window.location.pathname;
  const data = useStaticQuery(
    graphql`
      {
        datoCmsNavigation(sectionId: { eq: "navigation" }) {
          sectionId
          logo {
            url
            alt
          }
          menuItem {
            id
            name
            href
          }
        }
      }
    `
  );

  const {
    datoCmsNavigation: { sectionId, logo, menuItem },
  } = data;

  return (
    <NavBar id={sectionId}>
      <NavBarLogoWrapper>
        <a href="/">
          <img src={logo.url} alt={logo.test} />
        </a>
      </NavBarLogoWrapper>

      <NavBarList>
        {menuItem.map((item, index) => (
          <NavBarItem key={index}>
            <a href={item.href}> {item.name.toLowerCase()}</a>
          </NavBarItem>
        ))}
      </NavBarList>
    </NavBar>
  );
};

这是我的导航组件。有没有人知道我该如何处理?

1 个答案:

答案 0 :(得分:0)

window (and other global objects) are not available during the SSR 起,您的方法将在 gatsby 构建中失败。在你的场景中你不需要 useState 钩子,你只需要知道用户实际看到的是哪个页面。

Gatsby 中的顶级组件(页面)拥有 location property,它可以让你知道一堆数据,包括当前页面。您可以将该数据传递给您的 Navigation 组件以进行比较。例如:

const Blog = ({location, someOtherDestructuredProps}) => {

   return <section>
     <Navigation currentPage={location.pathname}/>
     <OtherComponent />
   </section>
}

然后,在您的导航组件中:

const Navigation = ({currentPage ="/"}) => {
  const pathName = window.location.pathname;
  const data = useStaticQuery(
    graphql`
      {
        datoCmsNavigation(sectionId: { eq: "navigation" }) {
          sectionId
          logo {
            url
            alt
          }
          menuItem {
            id
            name
            href
          }
        }
      }
    `
  );

  const {
    datoCmsNavigation: { sectionId, logo, menuItem },
  } = data;

  return (
    <NavBar id={sectionId}>
      <NavBarLogoWrapper>
        <a href="/">
          <img src={logo.url} alt={logo.test} />
        </a>
      </NavBarLogoWrapper>

      <NavBarList>
        {menuItem.map((item, index) => {
         
         if(currentPage == '/blog') return <DifferentNavBar />
         return <NavBarItem key={index}>
            <a href={item.href}> {item.name.toLowerCase()}</a>
          </NavBarItem>
        })}
      </NavBarList>
    </NavBar>
  );
};

在小改动中,重要的部分是为 currentPage 设置默认值(以防它丢失)和 map 循环的更改以返回不同的导航栏。当然,调整它以适应您的需求和要求。