【发布时间】: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