gpt4 book ai didi

reactjs - 使用具有嵌套路由的 Reach Router 无法解析参数

转载 作者:行者123 更新时间:2023-12-03 08:40:17 27 4
gpt4 key购买 nike

使用 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)

当我转到呈现 PostsView/g/123 时,它工作正常,并且我在 /g/123 中收到 123 的 groupId code>GroupPage,但是当我转到 /g/123/about 时,groupId 丢失,并且 params 为空(仍然在 GroupPage 内使用 useParams 时)。

如果我将 useParamsGroupPage 移动到嵌套的 AboutView 中,那么我就可以接收 params和来自 /g/123/aboutgroupId 但这很令人沮丧,因为我不想重复多个嵌套组件的逻辑,而宁愿将其放在外部 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。

除非有人知道更好的方法,否则我们可以认为这个问题已解决:)

关于reactjs - 使用具有嵌套路由的 Reach Router 无法解析参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62935495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com