React Router嵌套路由与搜索参数

huangapple go评论69阅读模式
英文:

React Router Nested Routing with Search Params

问题

在嵌套的React路由中使用搜索参数时,当我在/app页面上点击导航到/app/user的链接后,导航不起作用。

如果我在没有嵌套的情况下尝试,它是可以工作的。但是为什么在嵌套时它不起作用呢?

Codesandbox链接:CodeSandBox链接

<Routes>
    <Route path="/" element={<LandingPage />} />
    <Route path="/app" element={<Main />}>
      <Route path=":user" element={<User />} />
    </Route>
    <Route path="*" element={<PageNotFound />} />
  </Routes>
英文:

In nested React routing with search params, when I am on /app and after clicking on Link which navigates to /app/user. Navigation is not working.

If I am trying it without nesting, it is working but. But why it is not working when I am nesting it.

Codesandbox: CodeSandBox Link

&lt;Routes&gt;
    &lt;Route path=&quot;/&quot; element={&lt;LandingPage /&gt;} /&gt;
    &lt;Route path=&quot;/app&quot; element={&lt;Main /&gt;}&gt;
      &lt;Route path=&quot;:user&quot; element={&lt;User /&gt;} /&gt;
    &lt;/Route&gt;
    &lt;Route path=&quot;*&quot; element={&lt;PageNotFound /&gt;} /&gt;
  &lt;/Routes&gt;

答案1

得分: 4

请尝试这样做:

     <Routes>
        <Route path="/" element={<LandingPage />} />
        <Route path="/app" element={<Main />} />
        <Route path="/app/:user" element={<User />} />
        <Route path="*" element={<PageNotFound />} />
      </Routes>

如果你想要将User.js组件嵌套,你需要在Main.js中添加Outlet

import { Link, Outlet } from "react-router-dom";

export default function Main() {
  return (
    <div>
      <p>Main Page</p>
      <Link to="/app/ashish">点击进入用户页面</Link>

      <Outlet/>
    </div>
  );
}
英文:

try this

     &lt;Routes&gt;
        &lt;Route path=&quot;/&quot; element={&lt;LandingPage /&gt;} /&gt;
        &lt;Route path=&quot;/app&quot; element={&lt;Main /&gt;} /&gt;
        &lt;Route path=&quot;/app/:user&quot; element={&lt;User /&gt;} /&gt;
        &lt;Route path=&quot;*&quot; element={&lt;PageNotFound /&gt;} /&gt;
      &lt;/Routes&gt;

If you want the User.js component to be nested, you need to add Outlet in Main.js

import { Link, Outlet } from &quot;react-router-dom&quot;;

export default function Main() {
  return (
    &lt;div&gt;
      &lt;p&gt;Main Page&lt;/p&gt;
      &lt;Link to=&quot;/app/ashish&quot;&gt;Click to go to user page&lt;/Link&gt;

      &lt;Outlet/&gt;
    &lt;/div&gt;
  );
}

huangapple
  • 本文由 发表于 2023年7月27日 16:21:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定