reactjs 嵌套路由不呈现React Router v6

bweufnob  于 2023-01-25  发布在  React
关注(0)|答案(2)|浏览(199)

我尝试在react-router-dom版本6中将一个路径嵌套在另一个路径中,每当我尝试访问嵌套参数的页面(/blog/1)时,它会显示一个空白的非样式HTML页面,但当我将子路径放置到根目录ex./blog时,它会呈现得非常好。
带嵌套参数的工艺路线布局示例:

import React from "React";
import { BrowserRouter, Routes, Route } from "react-router-dom"

import Main from "./pages/Main.tsx";
import ChatGPT from "./pages/ChatGPT.tsx";

const App = () => {
    return (
        <BrowserRouter>
            <Routes>
                <Route index element={<Main />} />

                <Route path="blog">
                    <Route path=":id" element={<Blog />} />
                </Route>
            </Routes>
        </BrowserRouter>
    );
};

Main.tsx:

import React from "react";

const Main = () => {
    return (
        <div>
            <p>Home page</p>
        </div>
    );
};

export default Main;

Blog.tsx

import React from "react";
import { useParams } from "react-router-dom";

const Blog = () => {
    const params = useParams();
    const id = params.id;

    return (
        <div>
            <p>Blog ID: {id}</p>
        </div>
    );
};

export default Blog;

我尝试将<Outlet />标签放到组件的<div>标签的根目录中,但没有成功&我希望react能正确呈现嵌套参数的页面。我还使用Webpack的开发服务器来查看页面。
React:v18.2.0|React工艺路线DOM:版本6.6.2|网络包:v5.75.0|网络包-客户端:版本5.0.1|Webpack开发服务器:4.11.1

fkaflof6

fkaflof61#

MainBlog是默认导出,这意味着它们是默认导入。调用Main.defaultBlog.default可能返回undefined。只需渲染<Main /><Blog />

import React from "React";
import { BrowserRouter, Routes, Route } from "react-router-dom"
import Main from "./pages/Main";
import Blog from "./pages/Blog";

const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route index element={<Main />} />
        <Route path="blog">
          <Route path=":id" element={<Blog />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};
axkjgtzd

axkjgtzd2#

首先,从Main.defaultBlog.default中删除默认值

相关问题