英文:
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
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="/app" element={<Main />}>
<Route path=":user" element={<User />} />
</Route>
<Route path="*" element={<PageNotFound />} />
</Routes>
答案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
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="/app" element={<Main />} />
<Route path="/app/:user" element={<User />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
If you want the User.js
component to be nested, you need to add Outlet
in Main.js
import { Link, Outlet } from "react-router-dom";
export default function Main() {
return (
<div>
<p>Main Page</p>
<Link to="/app/ashish">Click to go to user page</Link>
<Outlet/>
</div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论