路由路径发生变化,但组件未按预期渲染

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

我已经使用 Material UI 抽屉和应用栏设置了基本的应用程序导航,并且抽屉中的所有列表项都可以使用 React Router 按预期正确更改路线并显示相应的组件。

enter image description here

App.js

function App() {
  const location = useLocation();

  function showComponentByPath(){
    let path = location.pathname;
  
    if (path === "/") {
      return <ProjectDashboard />
    }
  }

  return (
    <>
      <NavMenu />
      {showComponentByPath()}
      <Outlet />
    </>  
)}

export default App

Main.js

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<App />} errorElement={<ErrorPage />}>
      <Route path="projects/:id" element={<ProjectDetails />} />
      <Route path="tasks" element={<MyTasksView />} />
      <Route path="reviewtasks" element={<ReviewTasks />} />
      <Route path="myapplications" element={<MyApplications />} />
      <Route path="peerreviews" element={<PeerReviews />} />
      <Route path="reviewapplications" element={<ReviewApplication />} />
    </Route>
  ),
)

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <RouterProvider router={router} />
    </LocalizationProvider>
  </StrictMode>,
)

项目详细信息.jsx

function ProjectDetails() {
  console.log("I'm the ProjectDetails component");

  <div>
    <h1>
      Project Details
    </h1>
  </div>
}

export default ProjectDetails

当我尝试使用表格单元格作为嵌套路由(即项目/1)的链接时,问题就出现了。当我这样做时,表格单元格链接和路由都按预期工作,但组件的内容没有显示 - 尽管组件在安装组件时打印的 console.log 被渲染为明显。

enter image description here

TableCell 链接尝试

下面是我尝试将表格单元链接到所需路径(即“projects/:id”)的两种方法。这两种方法都会按预期更新路线,但不会显示组件的内容,因此我想包含这些方法以提供更多信息上下文。

我也没有同时使用这两种方法,只是想展示我所采取的方法。

<TableCell component={Link} to={"projects/1"}>{row.project_name}</TableCell>
<TableCell><Link to="projects/1">{row.project_name}</Link></TableCell>

可能对我自己或其他人查看此示例有帮助的问题:

  • 我的 React Router 设置或配置有问题吗?
  • 我尝试显示组件的方式是否存在状态/渲染问题?

我将提供尽可能多的屏幕截图,以帮助其他人在这里设置 React Router V6。

javascript reactjs react-router-dom vite
1个回答
0
投票

对于将来阅读本文的任何人来说,我是个白痴,忘记在我的组件中包含 HTML 的返回语句,因此尽管路由正确,但它没有显示。否则,我的 React Router 设置工作正常。

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