【发布时间】:2020-07-16 13:08:35
【问题描述】:
使用 Reach 路由器(不是 React 路由器!)我有 2 个嵌套路由:
/g/123
/g/123/about
其中 123 是 :groupId 参数:
import React from "react";
import { Router } from "@reach/router";
import GroupPage from "../components/dynamic-pages/group";
import PostsView from "../components/group/views/posts";
import AboutView from "../components/group/views/about";
const App = () => {
return (
<Router>
<GroupPage path="/g/:groupId">
<PostsView path="/" />
<AboutView path="/about" />
</GroupPage>
</Router>
);
};
export default App;
而在外部GroupPage 组件中,我需要使用:groupId 参数:
const GroupPage: React.FC<RouteComponentProps> = ({ children }) => {
debugger;
const params = useParams();
const groupId = params.groupId as string;
// query an API using groupId and store it in a context to be
// accessible to other nested components (such as AboutView and PostsView)
当我转到 /g/123 时,它会呈现 PostsView,它工作正常,并且我在 GroupPage 内收到 123 的 groupId,但是当我转到 /g/123/about 时,groupId 丢失并且params 为空(仍然在 GroupPage 内使用 useParams 时)。
如果我将useParams 从GroupPage 移动到嵌套的AboutView,那么我可以从/g/123/about 接收params 和groupId,但这很令人沮丧,因为我不想拥有重复多个嵌套组件的逻辑,宁愿将其放在外部 GroupPage 组件中(这需要 groupId 来查询 API 以获取组相关数据,然后我使用上下文使其可用于这些嵌套组件) .
我做错了什么,有没有办法实现我的需要?谢谢。
【问题讨论】:
标签: reactjs reach-router