May*_*ron 2 reactjs reach-router
使用 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;
Run Code Online (Sandbox Code Playgroud)
在外部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)
Run Code Online (Sandbox Code Playgroud)
当我转到/g/123呈现 时,PostsView它工作正常,并且我收到了groupId123 inside GroupPage,但是当我转到 时,/g/123/about它groupId丢失并且params为空(仍然在使用useParamsinside时GroupPage)。
如果我将useParamsfrom移至GroupPagenested 中AboutView,那么我可以接收paramsand groupIdfrom/g/123/about但这很令人沮丧,因为我不想重复多个嵌套组件的逻辑,而宁愿将其放在外部组件中GroupPage(需要groupId查询 API 以获取组相关数据,然后使用上下文使其可用于那些嵌套组件)。
我做错了什么吗?有办法实现我需要的吗?谢谢。
我发现我可以使用useMatch通配符来实现此目的:
const GroupPage: React.FC<RouteComponentProps> = ({ children }) => {
debugger;
const match = useMatch("/g/:groupId/*");
const groupId = match?.groupId as string;
Run Code Online (Sandbox Code Playgroud)
文档: https: //reach.tech/router/api/useMatch
这始终返回 PostsView 和 AboutView 路由的 groupId。
除非有人知道更好的方法,否则我们可以认为这个问题已解决:)
| 归档时间: |
|
| 查看次数: |
1299 次 |
| 最近记录: |