从另一个组件链接时,一个组件使用 useParams 的动态 URL 不起作用(MUI 面包屑与 react-router-dom)

问题描述 投票:0回答:1

假设有三个组成部分:

  • ComponentA(内容)
  • ComponentB (BlogRepo)
  • ComponentC(创建博客)

组件层次结构和它们的 URL 如下:

  • 内容(https://localhost/content)
    • BlogRepo (https://localhost/content/)
      • 创建博客 (https://localhost/content/createblog/?blogrepoId=xxxxxx))

路由在 app.js 中定义为使用

BrowserRouter
:

  <BrowserRouter>
      <Routes>
        <Route
          path="/content"
          element={
            <RequireAuth>
              <Content/>
            </RequireAuth>
          }
        />
        <Route
          path="/content/:bgid"
          element={
            <RequireAuth>
              <BlogsRepo/>
            </RequireAuth>
          }

        />
        <Route
          path="/createblog"
          element={
            <RequireAuth>
              <CreateBlog/>
            </RequireAuth>
          }
        />
        <Route path="*" element={<ErrorPage />} />
      </Routes>
  </BrowserRouter>

因为有很多博客 Repo(类似于空间),每个博客都由一个用于呈现页面的 id 标识。因此,对于 (https://localhost/content/) 我正在使用 useParams 将 blog_id 传递给 react-router-dom 并且它运行良好。

在创建博客时,我正在使用 https://mui.com/material-ui/react-breadcrumbs/ 来显示我们正在创建博客的 Blog Repo 的路径。它应该是这样的:

内容 / 博客回购 / createblog

现在使用上面的面包屑链接,我可以转到内容但是当尝试转到 Blog Repos 时,它使用正确的 URL 但无法显示内容。

用于博客回购的链接:

<Link
    underline="hover"
    sx={{ color: "primary", fontSize: "15px" }}
    href={`/content/${blogrepoid}`}
    >
    {blogreponame}
</Link>

我正在使用

location.search
获取 blogrepoid 并生成所需的字符串。但由于它没有映射到实际 blogrepoid 已呈现的 BlogRepos 组件,因此在单击 Blog Repos 链接后无法显示 https://localhost:3000/content/xxxxxx 的内容并且页面是显示空白。

有什么我们可以使这个链接起作用吗?

reactjs react-router-dom breadcrumbs mui5
1个回答
0
投票

我能够使用

navigate(-1)
修复它。尽管对这个解决方案不是很满意,但它确实有效。

这是我所做的:

在功能级别创建了以下一个:

const handleClick = () => {
    navigate(-1);
  };

然后放回面包屑

Link
下:

<Link
    underline="hover"
    sx={{ color: "primary", fontSize: "15px" }}
    onClick={handleClick}
>

出于某种原因,具有变量 id 的

href
breadcrumbs
下不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.