在 React 中,我可以使用 "useParams" 访问 URL 的 RESTful 组件吗?

In React, can I use "useParams" to access RESTful components of my URL?

我正在使用 React 16.13.0。在我的组件中,我可以像这样访问查询字符串参数(例如 /url?coop_id=23)

import { useParams } from "react-router-dom";
...
const { coop_id } = useParams();

但是,如何访问 RESTful 格式的参数?例如。如果我的 URL 是 /edit/23/home,React 获取“23”的方法是什么?我已经在我的 src/App.js 文件

中定义了路线
          <Switch>
            ...
            <Route path="/edit/:id/home" component={Edit} />

如果有用的话。

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>
        );
 };

您可以使用以下方法提取 ID:

console.log(this.props.match.params.id)

/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 组件中显示不同的内容。 查看 useParamsuseRouteMatch 了解更多详情。查看 https://reactrouter.com/web/example/nesting 中的示例,了解有关嵌套的详细信息。