【问题标题】:Gatsby server-side rendering of page with client-only routes, based on window locationGatsby 基于窗口位置的仅客户端路由页面的服务器端渲染
【发布时间】:2020-01-18 22:53:15
【问题描述】:

我正在处理一个 Gatsby 项目(一个语言学习博客),但由于服务器端渲染,我遇到了一个仅在生产版本中发生的问题。

我使用以下方案以编程方式为每篇博文生成一个页面: /posts/{post-name}。每个帖子还可以有许多子路径映射到 UI 中的打开选项卡。例如,/posts/important-spanish-verbs/lesson 将打开课程选项卡。每个页面都有一个/posts/{post-name}/*matchPath 属性,这些属性作为仅客户端路由处理,使用reach-router 实现。

使用gatsby develop,应用程序完全按照预期运行。当我访问/posts/some-post/podcast 时,它成功打开到播客选项卡,我可以看到活动选项卡设置正确。

问题在于,对于gatsby build && gatsby serve,当我重新加载一个直接导航到帖子内特定选项卡的 URL 时(手动访问整个 URL 或刷新),活动选项卡是 not 在 UI 中正确设置。

以下sn-p(高度简化和浓缩以演示问题)大致概述了问题:

function TabbedLayout({ children, basePath }) {
  return (
    <LocationProvider>
      {({ location }) => {
        return (
          <Fragment>
            <ul>
              React.Children.map(children, (child, index) => {
                const isActive = child.props.path === location.pathname
                console.log(`tab ${child.props.path} active? ${isActive}`)
                return <li className={isActive ? 'active' : 'inactive'}>{/* construct a link based on child props */}</li>
              })
            </ul>
            <Router basepath={basePath}>
              {children}
            </Router>
          </Fragment>
        )
      }}
    </LocationProvider>
}

当我在生产构建(使用 SSR)中运行使用上述方法的代码时会发生什么,例如当我访问 posts/example-post/lesson:

  • content 已通过 Reach 路由器正确呈现(即课程选项卡的 content 已打开)
  • 课程选项卡有课程inactive(错误)
  • 在控制台中,我看到 tab /posts/example-post/lesson active? true 打印出来,即使 CSS 类没有更新!

我已经尝试了所有我能想到的尝试更新 UI。一旦我单击不同的选项卡并且窗口位置更改没有刷新,一切都会更新正常并且活动选项卡 UI 按预期工作,但我似乎无法让它重新渲染基于isActive 变量。

有人知道解决或解决此问题的方法吗?

谢谢!

【问题讨论】:

    标签: javascript reactjs gatsby server-side-rendering reach-router


    【解决方案1】:

    我已设法找到解决该问题的方法,尽管无法详细了解问题实际发生的原因有点令人沮丧。

    如果我将标签&lt;li&gt;s(在首次使用 SSR 加载时未正确显示为活动/非活动)以检查我们是否在浏览器中,它可以工作:

    return typeof window !== 'undefined' && (
      <li className={isActive ? 'active' : 'inactive'}>
        {/* construct a link based on child props */}
      </li>
    )
    

    【讨论】:

      猜你喜欢
      • 2020-09-13
      • 2015-09-06
      • 1970-01-01
      • 2021-08-27
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      相关资源
      最近更新 更多