reactjs - 使用带有嵌套路由的到达路由器无法解析参数
问题描述
使用 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
,它工作正常,我收到groupId
123 inside GroupPage
,但是当我去丢失并且/g/123/about
为空(仍然在使用inside时)。groupId
params
useParams
GroupPage
如果我将useParams
from移动GroupPage
到 nestedAboutView
中,那么我可以接收params
and groupId
from/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;
文档:https ://reach.tech/router/api/useMatch
这始终返回 PostsView 和 AboutView 路由的 groupId。
除非有人知道更好的方法,否则我们可以考虑解决这个问题:)
推荐阅读
- asp.net-core - appsetting.json 已修改但仍返回旧值?
- javascript - 检查 v-data 表中是否存在购买 ID
- c - 管道没有读取它应该读取的内容
- c# - 如何将按钮从另一个表单添加到表单?C# 窗体
- fonts - SHX 字体规范和字体文件的许可
- c# - 在 dotnet core 中的 Wexflow 中创建与 Sql Server 中的任何表相关的简单流
- javascript - 我们观察到 user1 可以通过更改会话 ID 来访问 USER2
- spring-boot - JMSListener 转义 '.' 对于持久订阅
- elasticsearch - JAVA的createIndex elasticsearch高级rest客户端使设置不正确
- python - 混淆矩阵中的标签不正确