Reactjs 在React中,我可以使用;useParams“;要访问我的URL的RESTful组件?

Reactjs 在React中,我可以使用;useParams“;要访问我的URL的RESTful组件?,reactjs,routes,restful-url,Reactjs,Routes,Restful Url,我使用的是React 16.13.0。在我的组件中,我可以像这样访问查询字符串参数(例如/url?coop_id=23) 但是,如何以RESTful格式访问参数?例如,如果我的URL是/edit/23/home,那么获得“23”的反应方式是什么?我已经在src/App.js文件中定义了路由 <Switch> ... <Route path="/edit/:id/home" component

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

但是,如何以RESTful格式访问参数?例如,如果我的URL是/edit/23/home,那么获得“23”的反应方式是什么?我已经在src/App.js文件中定义了路由

          <Switch>
            ...
            <Route path="/edit/:id/home" component={Edit} />

...
如果有用的话。

从“react router”导入{useParams};
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>
        );
 };
从“react Router dom”导入{BrowserRouter as Router,Route,Link}; 常量组合=()=>{ 设{id}=useParams(); 返回( 投资组合组成部分 主题:{id}

); };
您可以使用以下方法提取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>
  );
}
函数编辑(){
//我们可以使用这里的'useParams'钩子访问
//URL的动态部分。
设{id}=useParams();
//我们可以进一步检查/:id之后是否有其他可用部件
//路径将包含这些部分
设{path}=useRouteMatch();
返回(
ID:{ID}
家
);
}
根据
/:id
之后是否有内容,您可以在
编辑组件中显示不同的内容。
查看
useParams
useRouteMatch
了解更多详细信息。有关嵌套的详细信息,请查看上的示例。

请参阅
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>
  );
}