我有一个使用 react-router-config 并使用 wrapper component 的应用程序重定向未经身份验证的用户。
我有一些需要使用路由/tasks/:id 的功能,但我无法访问 :id 值来执行必要的任务查找。
我的路线.js:
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}`}
/>
)
}
/>
);
}
在 App.js 中:
import React, { useState, useEffect } from "react";
import { BrowserRouter, Switch, withRouter } from "react-router-dom";
import AuthenticatedRoute from "./components/AuthenticatedRoute/AuthenticatedRoute";
import routes from "./routes";
function App(props) {
...
return (
<BrowserRouter>
<React.Suspense fallback={loading()}>
<Switch>
{routes.map((route, idx) => {
return route.component ? (
<AuthenticatedRoute
key={idx}
path={route.path}
exact={route.exact}
name={route.name}
appProps={props}
component={props => <route.component {...props} />}
/>
) : null;
})}
</Switch>
...
</React.Suspense>
</BrowserRouter>
最后我有我的Tasks.js:
import React, { useState, useEffect } from "react";
...
function Tasks(props) {
useEffect(() => {
onLoad();
}, []);
const onLoad = async () => {
console.log(JSON.stringify(props.match.params));
};
...
浏览到 localhost:3000/tasks/1。
props.match.params
在链上的每个组件中都是空的。 props.match.params.id
是 undefined
.我也试过匹配 {match.params.id}
但这在每个组件上也是未定义的。我可以看到
props.location.pathname
但这是完整的路径,我必须手动获取最后一段。我无法让它自动抓取 :id
从网址。编辑
原来我的例子太简单了,这实际上帮助我发现了问题。在我以前的版本中,当我有路线时:
{
path: "/tasks/:id",
name: "View Task",
component: Tasks
}
使用
useParams
实际上一切正常我可以得到 :id
值(value)。我在我的应用程序中实际拥有的以及似乎正在破坏它的是在路径中添加了一个额外的目录: {
path: "/tasks/edit/:id",
name: "View Task",
component: Tasks
}
我不确定这有什么不同,但是有额外的
/edit
似乎打破了useParams
最佳答案
react-router-dom
提供了一些方便的钩子(Hook)。在你的情况下,我建议 useParams()
(链接到文档)
import { useParams } from 'react-router-dom';
function MyComponent {
let { id } = useParams();
return (<p>{id}</p>);
}
我也可能会选择不使用
withRouter
如果你将使用 React Router 提供的钩子(Hook)
关于reactjs - react-router-dom 从带有自定义组件和额外路径的路由中获取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58924415/