我有一个应用程序,它使用react-router-config并使用wrapper component重定向未经身份验证的用户。
我有一些功能需要使用route /tasks/:id,但我无法访问:id值来执行必要的任务查找。
我的routes.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
,但这是完整的路径,我必须手动获取最后一段。我不能让它自动从url中获取:id
。
编辑原来我的例子太简化了,这实际上帮助我识别了问题。在我以前的版本中,当我有路由时:
{
path: "/tasks/:id",
name: "View Task",
component: Tasks
}
型
使用useParams
,一切都正常工作。我能够获得:id
值。我在应用程序中实际拥有的内容以及似乎破坏它的内容是在路径中添加一个额外的目录:
{
path: "/tasks/edit/:id",
name: "View Task",
component: Tasks
}
型
我不知道这有什么区别,但有额外的/edit
似乎打破了useParams
2条答案
按热度按时间3vpjnl9f1#
react-router-dom
提供了一些方便的钩子。对于您的情况,我建议使用useParams()
(链接到文档)字符串
如果你要使用React Router提供的钩子,我也可能选择不使用
withRouter
。w1jd8yoj2#
Martins的答案是正确的,适用于功能组件。我遇到了同样的问题,但是我使用了一个类组件(class Company extends Component),Martins的答案不适用于这种情况。如果你有一个类组件,你可以这样做:
字符串