首页 > 解决方案 > 使用带有嵌套路由的到达路由器无法解析参数

问题描述

使用 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,它工作正常,我收到groupId123 inside GroupPage,但是当我去丢失并且/g/123/about为空(仍然在使用inside时)。groupIdparamsuseParamsGroupPage

如果我将useParamsfrom移动GroupPage到 nestedAboutView中,那么我可以接收paramsand groupIdfrom/g/123/about但这很令人沮丧,因为我不想重复多个嵌套组件的逻辑,而是宁愿将它放在外部GroupPage组件中(这需要groupId查询 API 以获取组相关数据,然后我使用上下文使其可用于那些嵌套组件)。

我做错了什么,有没有办法实现我的需要?谢谢你。

标签: reactjsreach-router

解决方案


我发现我可以使用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。

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


推荐阅读