【发布时间】:2019-10-15 23:35:04
【问题描述】:
我有这种情况。
- 用户在地址栏中输入
/company/<company-id>。 - 由于应用与后端完全分离,因此需要预取公司。
- 普通用户流是
/login->/company/。我很好地处理了这个案例,只需导航到/company/<whatever id is first in the prefetch>就没有问题。 - 但是如果你加载 WITH id 呢?我有解决方案,但我觉得我在路由中误解了某些内容。
您可能会认为我的预取有效,并且下面的代码 sn-p 只有在 companyState.success 为真时才会触发。就像我说的,它正在工作。
我手动处理了这个,由
// pretty sure i can handle this with regex better to capture other cases
// but that's beside the point for the scope of this question
const urlId = +location.pathname.replace("/company/", "")
const checkCompany = !!companyState.data.find(d => d.id === urlId)
if(checkCompany){
company.set(urlId)
}
else{
navigate("/404")
}
如果company.set(<company:id>) 确实更新了,它会预先获取视图所需的所有其他内容。而且,company 是一个自定义上下文挂钩,因此它在我的应用程序中随处可见。
有没有更好的方法来处理这个问题?手动检查路径名似乎是 hack-y。
您可以假设我的gatsby_node.js 具有正确的定义以允许客户端路由。
这是我的路由定义:(这是我放在 pages 文件夹中的)
const DashboardPage = () => (
<ProtectedRoute>
<Router>
<Company path="/company/*" />
</Router>
</ProtectedRoute>
)
终于在components文件夹下,
const Company = ({location}) => (
<Router>
<Main path="/:companyId">
<Summary path="/" />
.... other dashboard routes
</Main>
</Router>
)
【问题讨论】:
标签: javascript reactjs gatsby reach-router