如何忽略反应路由器的最后 url 部分?
How to ignore last url part with react router?
我想用react router根据URL的第一部分显示一个页面,因为URL的最后一部分是持有一个ID。我怎样才能读出最后一部分,现在我正在使用 string.split("/").pop()
URL
http://localhost:3003/profile/313a2333
路由器
<Routes>
<Route path="/profile" element={<Profile/>} />
</Routes>
按如下方式定义您的 Route
:
<Route path="/profile/:user_id">
然后就可以得到Profile
组件中的第二个参数了
import { useParams } from 'react-router-dom';
const params: any = useParams();
const user_id = params.user_id;
如果您不关心第二个路径段,只想根据第一个路径段进行匹配,那么请使用 "*"
通配符匹配器。
<Routes>
<Route path="/profile/*" element={<Profile/>} />
</Routes>
如果您需要捕获第二个路径段值,请为其提供一个参数名称。
<Routes>
<Route path="/profile/:id" element={<Profile/>} />
</Routes>
使用 useParams
挂钩访问路由组件中的路由路径参数。
const { id } = useParams();
我想用react router根据URL的第一部分显示一个页面,因为URL的最后一部分是持有一个ID。我怎样才能读出最后一部分,现在我正在使用 string.split("/").pop()
URL http://localhost:3003/profile/313a2333
路由器
<Routes>
<Route path="/profile" element={<Profile/>} />
</Routes>
按如下方式定义您的 Route
:
<Route path="/profile/:user_id">
然后就可以得到Profile
组件中的第二个参数了
import { useParams } from 'react-router-dom';
const params: any = useParams();
const user_id = params.user_id;
如果您不关心第二个路径段,只想根据第一个路径段进行匹配,那么请使用 "*"
通配符匹配器。
<Routes>
<Route path="/profile/*" element={<Profile/>} />
</Routes>
如果您需要捕获第二个路径段值,请为其提供一个参数名称。
<Routes>
<Route path="/profile/:id" element={<Profile/>} />
</Routes>
使用 useParams
挂钩访问路由组件中的路由路径参数。
const { id } = useParams();