我使用的是React 16.13.0。在我的组件中,我可以像这样访问查询字符串参数(例如/url?coop_id=23
import { useParams } from "react-router-dom";
...
const { coop_id } = useParams();但是,如何访问RESTful格式的参数?例如,如果我的URL是/edit/23/home,那么获取"23“的React方法是什么?我已经在src/App.js文件中定义了路由
<Switch>
...
<Route path="/edit/:id/home" component={Edit} />如果有用的话。
发布于 2020-07-19 01:00:39
import { useParams} from "react-router";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const Portfolio = () => {
let { id } = useParams();
return (
<div>
Portfolio component
<p>Topic: {id}</p>
</div>
);
};发布于 2020-07-19 01:10:26
您可以使用以下命令提取id:
console.log(this.props.match.params.id)发布于 2020-07-19 01:34:41
在/edit/:id/home的情况下,您可以在组件中嵌套路由以供编辑。
编辑组件可能类似于:
function Edit() {
// We can use the `useParams` hook here to access
// the dynamic pieces of the URL.
let { id } = useParams();
// We can further check if there are other parts available after the /:id
// the path will contain those parts
let { path } = useRouteMatch();
return (
<div>
<h3>ID: {id}</h3>
<Switch>
<Route path={`${path}/home`}>home</Route>
</Switch>
</div>
);
}根据/:id之后是否有内容,您可以在Edit组件中显示不同的内容。有关更多详细信息,请查看useParams和useRouteMatch。有关嵌套的详细信息,请查看https://reactrouter.com/web/example/nesting上的示例。
https://stackoverflow.com/questions/62971220
复制相似问题