React路由器V6-从父路线通往嵌套路线,而无需显示父路线
我正在尝试在我的router.js
中使用此代码的嵌套路由:
return (
<Routes>
<Route path="" element={<Home />} />
<Route path="/DriverPage/*" element={<DriverPage />}>
<Route path="DriverSignUp" element={<DriverSignUp />}/>
<Route path="DriverLogin" element={<DriverLogIn />} />
</Route>
<Route path="/PassengerPage/*" element={<PassengerPage />} />
</Routes>
这是driverpage.js.js
组件中的代码,该代码是父路由
return (
<>
<div className="driver-auth">
<button onClick={ ()=>navigate("DriverSignUp",{replace:true}) }> Sign up </button>
<button onClick={ ()=>navigate("DriverLogin",{replace:true}) }> Sign in </button>
</div>
<Outlet />
</>
:问题是我想 在单击按钮时用嵌套组件替换父组件,因为我不希望父母继续显示。
这就是为什么我尝试使用导航(“ driverlogin”,{replace:true})
,但这无济于事,我在单击时看到父母和子路由。
我认为这是因为我在父路线路径中拥有的/*
,这意味着即使只是开始匹配,它也匹配它。
因此,是否有任何解决方案仍然使用嵌套路线,还是我不应该使用嵌套?
还有一个问题是:为什么替换不起作用?
谢谢!
I'm trying to use nested routes for this code here in my Router.js
:
return (
<Routes>
<Route path="" element={<Home />} />
<Route path="/DriverPage/*" element={<DriverPage />}>
<Route path="DriverSignUp" element={<DriverSignUp />}/>
<Route path="DriverLogin" element={<DriverLogIn />} />
</Route>
<Route path="/PassengerPage/*" element={<PassengerPage />} />
</Routes>
And this is the code in the DriverPage.js
component which is the parent route:
return (
<>
<div className="driver-auth">
<button onClick={ ()=>navigate("DriverSignUp",{replace:true}) }> Sign up </button>
<button onClick={ ()=>navigate("DriverLogin",{replace:true}) }> Sign in </button>
</div>
<Outlet />
</>
The problem is that I want to replace the parent component with the nested component when the buttons are clicked, because I don't want the parent to keep showing.
That's why I've tried to use navigate("DriverLogin",{replace:true})
but it's not helping and I see both the parent and the child route when clicking.
I think It's because of the /*
I have in the parent route path, which means that it matches even if just the begining matches.
So, is there any solution for this with still using nested routes or should I not use the nesting?
And one more question is: Why isn't the replace working ?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想查看此代码示例,请查看我的sandbox
You can get that result in 2 ways
**1. you can define those routes individual **
**2. Define the nested routes like this **
Parent component
If you want to view this code example then checkout my sandbox
You can get that result in 2 ways
**1. you can define those routes individual **
**2. Define the nested routes like this **
Parent component
导航(“ driverlogin”)
将获得父母的路径。您应该使用
导航(“/driverlogin”)
如果您不想获得父母的路径navigate("DriverLogin")
will get the parent's path.You should use
navigate("/DriverLogin")
if you don't want to get the parent's path