Reactjs 使用自定义组件和额外路径从路由获取id
我有一个应用程序,它使用react路由器配置并使用重定向未经验证的用户 我有一些功能需要使用route/tasks/:id,但我无法访问:id值以执行必要的任务查找 My routes.js:Reactjs 使用自定义组件和额外路径从路由获取id,reactjs,react-router-dom,Reactjs,React Router Dom,我有一个应用程序,它使用react路由器配置并使用重定向未经验证的用户 我有一些功能需要使用route/tasks/:id,但我无法访问:id值以执行必要的任务查找 My routes.js: import React from "react"; ... const Tasks = React.lazy(() => import("./Components/Tasks")); ... const routes = [ { path: "/tasks/edit/:id",
import React from "react";
...
const Tasks = React.lazy(() => import("./Components/Tasks"));
...
const routes = [
{
path: "/tasks/edit/:id",
name: "View Task",
component: Tasks
}
...
];
export default routes;
然后我有AuthenticatedRoute.js
:
import React from "react";
import { Route, Redirect } from "react-router-dom";
export default function AuthenticatedRoute({
component: C,
appProps,
...rest
}) {
return (
<Route
{...rest}
render={props =>
appProps.isAuthenticated ? (
<C {...props} {...appProps} />
) : (
<Redirect
to={`/login?redirect=${props.location.pathname}${props.location.search}`}
/>
)
}
/>
);
}
浏览到localhost:3000/tasks/1<代码>props.match.params在链上的每个组件中都是空的<代码>props.match.params.id是未定义的
。我还尝试了使用{match.params.id}
进行匹配,但在每个组件上都没有定义
我可以看到props.location.pathname
,但这是完整的路径,我必须手动获取最后一段。我无法让它自动从url获取:id
编辑
事实证明,我的示例过于简化,这实际上帮助我确定了问题所在。在我之前的版本中,当我有路线时:
{
path: "/tasks/:id",
name: "View Task",
component: Tasks
}
使用useParams
我可以得到:id
值,实际上一切都正常。我在我的应用程序中实际拥有的以及似乎破坏它的是在路径中添加一个额外的目录:
{
path: "/tasks/edit/:id",
name: "View Task",
component: Tasks
}
我不确定这会有什么不同,但使用额外的
/edit
似乎打破了useparms
反应路由器dom
提供了一些方便的挂钩。在你的情况下,我建议(链接到文档)
从'react router dom'导入{useParams};
功能部件{
设{id}=useParams();
返回({id});
}
如果您要使用React Router提供的钩子,我可能也会选择不使用
with Router
,请尝试使用const{id}=useParams()代码>。从react-router-dom相应地导入useParams。你能提供一个codesandbox或其他东西吗?创建codesandbox时,我想我找到了问题所在。我的路线有一条额外的路,似乎要断了。谢谢。我更新了我的问题。我在我的应用程序中创建了一个新页面,只有一个基本路径/test/:id
,您的代码正常工作。当我添加了额外的目录(这是我的应用程序实际拥有的)/test/edit/:id
时,它不再工作。让{id}=useParams()
应该工作。我的路径是/student/general/request/:id。我可以获取id,但我需要检查它是否是通用的。有什么办法可以抓住这条路的大致部分吗?@Ravisara,谢谢。在我的代码中,可以使用“let{id,type}=useParams()”来完成
{
path: "/tasks/:id",
name: "View Task",
component: Tasks
}
{
path: "/tasks/edit/:id",
name: "View Task",
component: Tasks
}
import { useParams } from 'react-router-dom';
function MyComponent {
let { id } = useParams();
return (<p>{id}</p>);
}