代码之家  ›  专栏  ›  技术社区  ›  Dylan L.

React Router v6链接组件不更改根url处的页面

  •  1
  • Dylan L.  · 技术社区  · 4 年前

    我创造了一个 Link Post 链接到 Post Page .单击链接时,url位于 '/' 链接无法正常工作,它在url中显示了正确的链接。 http://localhost:3000/posts/624a771b42211849eaada885 但是页面不会重定向,唯一有效的方法是刷新页面。然而,如果我在 Popular Posts 页面链接正常工作。需要明确的是,帖子位于一个名为Posts的组件中,该组件显示所有帖子。Posts组件是一个跨许多组件的共享组件,例如主页( '/' )和热门帖子( /popular )该链接适用于所有其他页面,但在 '/'

    下面是 链接 .

    <Link to={`/posts/${_id}`}>
      <h2 className='post-title'>{title}</h2>
    </Link>
    

    我的路线设置如下:

    <Route element={!token ? <Navigate replace to='/login' /> : <Navbar />}>
      <Route
        path='/'
        element={<Home />}
      >
        <Route
          path='/popular'
          element={<Popular />}
        />
        <Route 
          path='/posts/:postId' 
          element={<PostPage />} 
        />
      </ Route>
    </Route>
    

    在我的导航栏中,我有:

    const Navbar = () => {
    
      return(
        <>
          <nav>
          </nav>
          <Outlet />
        </>
      )
    }
    

    最后,在我家。我有这个:

    const Home = () => {
      return (
        <div>content</div>
        <div>content</div>
        <div className='home-posts-container'>
              {window.location.pathname === '/' ? <PopularPosts /> : 
               <Outlet />}
        </div>
        <div>content</div>
      )
    }
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Drew Reese    4 年前

    据我所知,你的 Home 组件

    const Home = () => {
      return (
        <>
          <div>content</div>
          <div>content</div>
          <div className="home-posts-container">
            {window.location.pathname === "/" ? <PopularPosts /> : <Outlet />}
          </div>
          <div>content</div>
        </>
      );
    };
    

    要渲染 PopularPosts 组成部分 确切地 当路径是 "/" ,否则要渲染其中一条匹配的嵌套管线。

    问题是,通过上述实施 Outlet 路径更改时不渲染,因此所有嵌套路由都不可匹配。

    看来你想要 组件要成为布局布线,它应该呈现所有 div 元素和内容, 只是 这个 出口 .移动 大众主义者 组件转换为索引路由。

    const Home = () => {
      return (
        <>
          <div>content</div>
          <div>content</div>
          <div className="home-posts-container">
            <Outlet />
          </div>
          <div>content</div>
        </>
      );
    };
    

    ...

    <Routes>
      <Route element={!token ? <Navigate replace to="/login" /> : <Navbar />}>
        <Route path="/" element={<Home />}>
          <Route index element={<PopularPosts />} />
          <Route path="/popular" element={<Popular />} />
          <Route path="/posts/:postId" element={<PostPage />} />
        </Route>
      </Route>
    </Routes>
    

    Edit react-router-v6-link-component-not-changing-the-page-at-root-url

    有关更多信息,请参阅: